slash_commands.py 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. """Gateway slash-command handlers for GatewayRunner: lifted out of ``gateway/run.py`` into a mixin
  2. so ``self._handle_*_command`` keeps resolving via the MRO. Cohesive clusters live in the sibling
  3. mixins (``slash_commands_model/_session/_status/_goals``); this module keeps the shared helpers plus
  4. the one-off commands. run.py helpers are imported lazily."""
  5. from __future__ import annotations
  6. import asyncio
  7. import contextlib
  8. import dataclasses
  9. import inspect
  10. import logging
  11. import os
  12. import re
  13. import shlex
  14. import sys
  15. import time
  16. from datetime import datetime
  17. from pathlib import Path
  18. from typing import Optional, Union
  19. from agent.i18n import t
  20. from gateway.config import HomeChannel, Platform, PlatformConfig, persist_home_channel
  21. from gateway.platforms.base import EphemeralReply
  22. from gateway.platforms.event import MessageEvent
  23. from gateway.session import AsyncSessionStore
  24. from gateway.session_transcript import TranscriptReadError
  25. from gateway.slash_commands_goals import GatewayGoalCommandsMixin
  26. from gateway.slash_commands_model import GatewayModelCommandsMixin
  27. from gateway.slash_commands_session import GatewaySessionCommandsMixin
  28. from gateway.slash_commands_login import GatewayLoginCommandsMixin
  29. from gateway.slash_commands_status import GatewayStatusCommandsMixin, history_unreadable
  30. from hermes_cli.config import atomic_config_write, cfg_get
  31. from utils import atomic_json_write, is_truthy_value
  32. logger = logging.getLogger("gateway.run")
  33. # /rollback result keys -> i18n line for files the safe restore left alone.
  34. _ROLLBACK_SKIP_LINES = (("skipped_user_edits", "gateway.rollback.kept_user_edits"),
  35. ("skipped_oversize", "gateway.rollback.kept_oversize"),
  36. ("failed_deletes", "gateway.rollback.failed_deletes"))
  37. # /busy input modes -> (status-card behavior key, set-confirmation behavior key); text via t().
  38. _BUSY_MODE_BEHAVIOR = {
  39. "queue": ("gateway.busy.behavior_queue_short", "gateway.busy.behavior_queue_long"),
  40. "steer": ("gateway.busy.behavior_steer_short", "gateway.busy.behavior_steer_long"),
  41. "interrupt": ("gateway.busy.behavior_interrupt_short", "gateway.busy.behavior_interrupt_long"),
  42. }
  43. # /diff argument -> diff mode (unknown args leave the mode unchanged).
  44. _DIFF_MODE_BY_ARG = {**dict.fromkeys(("staged", "--staged", "cached", "--cached"), "staged"),
  45. **dict.fromkeys(("all", "--all", "head"), "all"), "session": "session"}
  46. # /voice subcommand -> stored mode (None = auto-TTS disabled), confirmation i18n key.
  47. _VOICE_MODE_BY_ARG = {
  48. **dict.fromkeys(("on", "enable"), ("voice_only", "gateway.voice.enabled_voice_only")),
  49. **dict.fromkeys(("off", "disable"), ("off", "gateway.voice.disabled_text")),
  50. "tts": ("all", "gateway.voice.tts_enabled")}
  51. # /footer argument -> new enabled state ("" toggles; anything else is a usage error).
  52. _FOOTER_STATE_BY_ARG = {**dict.fromkeys(("on", "enable", "true", "1"), True),
  53. **dict.fromkeys(("off", "disable", "false", "0"), False)}
  54. # /approve modifier tokens -> approval choice (default "once").
  55. _APPROVE_CHOICE_BY_ARG = {**dict.fromkeys(("always", "permanent", "permanently"), "always"),
  56. **dict.fromkeys(("session", "ses"), "session")}
  57. _WINDOWS_UPDATE_HELPER = """
  58. import os, subprocess, sys
  59. output_path, exit_code_path, cmd = sys.argv[1], sys.argv[2], sys.argv[3:]
  60. env = dict(os.environ, PYTHONUNBUFFERED="1")
  61. with open(output_path, "wb") as f:
  62. rc = subprocess.Popen(cmd, stdout=f, stderr=subprocess.STDOUT, env=env).wait(timeout=3600)
  63. # Temp + replace: the gateway watcher polls the exit code and reads an empty file as failure.
  64. with open(exit_code_path + ".tmp", "w", encoding="utf-8") as f:
  65. f.write(str(rc))
  66. os.replace(exit_code_path + ".tmp", exit_code_path)
  67. """.strip()
  68. def _nested_dict(root: dict, *keys: str) -> dict:
  69. """Walk/create ``root[k1][k2]...`` as dicts, replacing any non-dict value on the path."""
  70. for k in keys:
  71. if not isinstance(root.get(k), dict):
  72. root[k] = {}
  73. root = root[k]
  74. return root
  75. def _write_raw_config_leaf(config_path: Path, keys: tuple, value) -> None:
  76. """Set one leaf through a strict raw round-trip. The behavioral read is fail-open (``{}``) and
  77. expanded, so writing it back wipes the file after a read error and persists ``${VAR}`` values."""
  78. from hermes_cli.config import read_user_config_raw
  79. raw = read_user_config_raw(config_path)
  80. *parents, leaf = keys
  81. _nested_dict(raw, *parents)[leaf] = value
  82. atomic_config_write(config_path, raw)
  83. def _preview(text: str, limit: int = 60) -> str:
  84. return text[:limit] + ("..." if len(text) > limit else "")
  85. def _execute(command: str, **ctx_kwargs):
  86. """Run *command* through the shared slash executor on the gateway surface."""
  87. from hermes_cli.slash_exec import CommandContext, execute_command
  88. return execute_command(command, CommandContext(surface="gateway", **ctx_kwargs))
  89. def _restart_notify_payload(event: MessageEvent) -> dict:
  90. """Requester routing info so the new gateway process can notify them once back online.
  91. ``profile`` is persisted so the notice leaves through the requester's own profile bot after the
  92. restart (a bare platform lookup would resolve the default profile's adapter)."""
  93. source = event.source
  94. data = {"platform": source.platform.value if source.platform else None,
  95. "chat_id": source.chat_id, "chat_type": source.chat_type}
  96. if source.delivered_via_upstream_relay is True:
  97. data["delivered_via_upstream_relay"] = True
  98. data.update({k: getattr(source, k) for k in ("user_id", "scope_id") if getattr(source, k)})
  99. optional = (("thread_id", source.thread_id), ("message_id", event.message_id),
  100. ("profile", getattr(source, "profile", None)))
  101. data.update({k: v for k, v in optional if v})
  102. return data
  103. def _spawn_detached_update(hermes_cmd, output_path, exit_code_path) -> None:
  104. """Spawn ``hermes update --gateway`` detached so it survives the gateway restart it may trigger.
  105. setsid is portable (works where ``systemd-run --user`` lacks a D-Bus session); ``--gateway``
  106. enables file-based IPC so interactive prompts are forwarded; PYTHONUNBUFFERED lets the gateway
  107. stream output live. Windows has no setsid: an inline helper runs the updater as a module under
  108. this interpreter (not venv\\Scripts\\hermes.exe — that shim holds its own file open, and the
  109. update must replace it), redirects both outputs to one file and writes the exit code."""
  110. import shutil
  111. import subprocess
  112. if sys.platform == "win32":
  113. from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
  114. subprocess.Popen(
  115. [sys.executable, "-c", _WINDOWS_UPDATE_HELPER, str(output_path), str(exit_code_path),
  116. sys.executable, "-m", "hermes_cli.main", "update", "--gateway"],
  117. # detached-spawn: ok — /update runs `hermes update`, which must outlive the gateway it restarts
  118. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **windows_detach_popen_kwargs())
  119. return
  120. hermes_cmd_str = " ".join(shlex.quote(part) for part in hermes_cmd)
  121. update_cmd = (
  122. f"PYTHONUNBUFFERED=1 {hermes_cmd_str} update --gateway"
  123. f" > {shlex.quote(str(output_path))} 2>&1; "
  124. # Avoid `status=$?`: `status` is read-only in zsh and this template is reused in
  125. # macOS/zsh operator wrappers, so keep it zsh-safe even though bash runs it here.
  126. # Temp + mv: the gateway watcher polls the exit code and reads an empty file as failure.
  127. f"rc=$?; printf '%s' \"$rc\" > {shlex.quote(str(exit_code_path) + '.tmp')}"
  128. f" && mv -f {shlex.quote(str(exit_code_path) + '.tmp')} {shlex.quote(str(exit_code_path))}")
  129. # Preferred: setsid creates a new session, fully detached; fallback start_new_session=True
  130. # calls os.setsid() in the child.
  131. setsid_bin = shutil.which("setsid")
  132. argv = [setsid_bin, "bash", "-c", update_cmd] if setsid_bin else ["bash", "-c", update_cmd]
  133. # detached-spawn: ok — /update runs `hermes update`, which must outlive the gateway it restarts
  134. subprocess.Popen(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
  135. def _home_thread_from_source(source) -> Optional[str]:
  136. """The thread id /sethome should persist on the home target, or None. Slack thread-per-message
  137. keying stamps a top-level message's own id as ``source.thread_id`` (a session key, not a
  138. location); persisting it would pin HOME to that ephemeral thread. A thread id equal to the
  139. message's own id is synthetic and dropped; a real thread (id = parent's) is kept."""
  140. thread_id = getattr(source, "thread_id", None)
  141. if not thread_id:
  142. return None
  143. synthetic = (getattr(source, "platform", None) == Platform.SLACK and getattr(source, "message_id", None)
  144. and str(thread_id) == str(source.message_id))
  145. return None if synthetic else str(thread_id)
  146. class GatewaySlashCommandsMixin(
  147. GatewayLoginCommandsMixin,
  148. GatewayModelCommandsMixin,
  149. GatewaySessionCommandsMixin,
  150. GatewayStatusCommandsMixin,
  151. GatewayGoalCommandsMixin):
  152. """In-session slash-command handlers for GatewayRunner (plus the helpers the sibling mixins share)."""
  153. async_session_store: AsyncSessionStore
  154. # ------------------------------------------------------------------ shared helpers
  155. def _cached_agent_for(self, session_key: str, *, lockless_fallback: bool = False):
  156. """Peek the cached AIAgent for *session_key* without evicting it, or None. Entries are
  157. ``(agent, signature, ...)`` tuples (bare agents from test doubles accepted). Historical callers
  158. read the cache ONLY under ``_agent_cache_lock`` and got None when a fixture that skipped
  159. ``__init__`` had no lock; the manual codex ``/compress`` path was the one exception that read
  160. lock-free (``lockless_fallback=True``)."""
  161. cache = getattr(self, "_agent_cache", None)
  162. lock = getattr(self, "_agent_cache_lock", None)
  163. if cache is None or (lock is None and not lockless_fallback):
  164. return None
  165. try:
  166. if lock:
  167. with lock:
  168. entry = cache.get(session_key)
  169. else:
  170. entry = cache.get(session_key)
  171. except Exception:
  172. return None
  173. return (entry[0] if entry else None) if isinstance(entry, (tuple, list)) else entry or None
  174. def _resident_agent_for(self, session_key: str):
  175. """The live running agent for *session_key*, else the cached one, else None. The pending
  176. sentinel (a run that is starting) never counts as a usable agent."""
  177. from gateway.run import _AGENT_PENDING_SENTINEL
  178. agent = self._running_agents.get(session_key)
  179. if agent is not None and agent is not _AGENT_PENDING_SENTINEL:
  180. return agent
  181. return self._cached_agent_for(session_key)
  182. @staticmethod
  183. def _session_db_unavailable_reply() -> str:
  184. from hermes_state import format_session_db_unavailable
  185. return format_session_db_unavailable(prefix=t("gateway.shared.session_db_unavailable_prefix"))
  186. def _reply_metadata(self, event: MessageEvent):
  187. """Thread/reply metadata for an outbound send anchored on *event*."""
  188. return self._thread_metadata_for_source(event.source, self._reply_anchor_for_event(event))
  189. def _adapter_and_key_for(self, event: MessageEvent):
  190. """``(adapter, session_key)`` for the event's source, either None when no source. The source's
  191. OWN transport (profile-aware, fail-closed) — ``self.adapters`` is the default profile's map."""
  192. if not event.source:
  193. return None, None
  194. return self._delivery_adapter_for(event.source), self._session_key_for_source(event.source)
  195. def _telegramized_command_reply(self, event: MessageEvent, text: str) -> str:
  196. from gateway.run import _telegramize_command_mentions
  197. return _telegramize_command_mentions(text, getattr(getattr(event, "source", None), "platform", None))
  198. def _checkpoint_manager(self, source=None):
  199. """A CheckpointManager from a local session's frozen policy, else gateway config; None when disabled."""
  200. from gateway.run import _checkpoint_agent_kwargs, _load_gateway_config
  201. from gateway.session_authorities import active_authority
  202. from gateway.session_policy import policy_for_source
  203. from tools.checkpoint_manager import CheckpointManager
  204. policy = policy_for_source(self, source) if source is not None else None
  205. cp = _checkpoint_agent_kwargs(policy.config(active_authority(self), secrets=False) if policy
  206. else _load_gateway_config())
  207. if not cp["checkpoints_enabled"]:
  208. return None
  209. # AIAgent kwargs are ``checkpoint_<field>``; CheckpointManager takes the bare field names.
  210. fields = {k[len("checkpoint_"):]: v for k, v in cp.items() if k.startswith("checkpoint_")}
  211. return CheckpointManager(enabled=True, **fields)
  212. def _write_approval_setter(self, section: str, event: MessageEvent):
  213. """``set_mode_fn`` for /memory and /skills: persist ``<section>.write_approval``. Raw read is
  214. correct for the write-back round-trip (merged defaults must not be persisted back to the
  215. user's file); the cached agent is dropped so the setting takes effect next message."""
  216. from gateway.run import _gateway_config_home
  217. # Persist to config (default) unless --session opted out, mirroring the text /model command path
  218. # above so a picked model survives across sessions like a typed one (#49066).
  219. from hermes_cli.config import read_user_config_raw
  220. config_path = _gateway_config_home() / "config.yaml"
  221. session_key = self._session_key_for_source(event.source)
  222. def _set_approval(enabled: bool):
  223. user_config = read_user_config_raw(config_path)
  224. user_config.setdefault(section, {})["write_approval"] = bool(enabled)
  225. atomic_config_write(config_path, user_config)
  226. # Evict any cached agent for this session so the next message rebuilds with the correct
  227. # session_id end-to-end — mirrors /branch and /reset. Without this, the cached AIAgent (and its
  228. # memory provider, which cached `_session_id` during initialize()) keeps writing into the wrong
  229. # session's record. See #6672.
  230. self._evict_cached_agent(session_key)
  231. return _set_approval
  232. async def _deliver_approval_confirmation(self, event: MessageEvent, confirmation_text: str, verb: str):
  233. """Return *confirmation_text* for normal delivery, or push it on native-streaming adapters
  234. (WeCom msgtype:"stream"), which need it sent directly with control-lane metadata (reliable
  235. proactive send, not the finalized reply stream). ``is not True``: mocks auto-create attrs."""
  236. source = event.source
  237. adapter = self._delivery_adapter_for(source) # the receiving bot, not the default profile's
  238. if adapter:
  239. adapter.resume_typing_for_chat(source.chat_id) # agent is about to continue
  240. if getattr(adapter, "SUPPORTS_NATIVE_STREAMING", False) is not True:
  241. return confirmation_text
  242. if adapter:
  243. try:
  244. await adapter.send(
  245. source.chat_id, confirmation_text, reply_to=event.message_id,
  246. metadata={"is_approval_prompt": True, "force_proactive_send": True})
  247. except Exception as exc:
  248. logger.warning("Failed to send /%s confirmation to %s: %s", verb, source.chat_id,
  249. exc, exc_info=True)
  250. return None
  251. def _typed_command_prefix_for(self, platform) -> str:
  252. """The prefix users can always type to reach Hermes commands (adapter ``typed_command_prefix``,
  253. default "/"). Slack and Matrix use "!" because typed "/" is blocked/reserved there; their
  254. adapters rewrite "!command" to "/command"."""
  255. adapter = self.adapters.get(platform) if getattr(self, "adapters", None) else None
  256. return getattr(adapter, "typed_command_prefix", "/") if adapter is not None else "/"
  257. def _terminal_cwd(self) -> str:
  258. from tools.terminal_scope import terminal_env
  259. return terminal_env("TERMINAL_CWD", str(Path.home()))
  260. @staticmethod
  261. def _display_config_target(event: MessageEvent):
  262. """``(config.yaml path, platform config key)`` for the per-platform display settings."""
  263. from gateway.run import _gateway_config_home, _platform_config_key
  264. return _gateway_config_home() / "config.yaml", _platform_config_key(event.source.platform)
  265. async def _handle_profile_command(self, event: MessageEvent) -> str:
  266. """Handle /profile — show the profile serving this source and its home. On a multiplexed
  267. gateway the process-level profile is the multiplexer's own ("default" in every chat), so
  268. with ``multiplex_profiles`` on report ``source.profile`` and resolve home under that
  269. profile's runtime scope; when off the stamp is ignored, mirroring ``_run_agent``."""
  270. from hermes_constants import display_hermes_home
  271. source = getattr(event, "source", None)
  272. profile_name = display = ""
  273. if getattr(getattr(self, "config", None), "multiplex_profiles", False):
  274. profile_name = (getattr(source, "profile", "") or "").strip()
  275. try:
  276. from gateway.run import _profile_runtime_scope
  277. with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
  278. display = display_hermes_home()
  279. except Exception:
  280. display = display_hermes_home()
  281. # Shared executor resolves process-level fallbacks; the multiplexed per-source overrides
  282. # (when any) ride in via options.
  283. reply = _execute("profile", options={"profile_name": profile_name, "home_display": display})
  284. return "\n".join([t("gateway.profile.header", profile=reply.data["profile"]),
  285. t("gateway.profile.home", home=reply.data["home"])])
  286. async def _handle_whoami_command(self, event: MessageEvent) -> str:
  287. """Handle /whoami — platform, DM-vs-group scope, tier and runnable commands (always allowed)."""
  288. from gateway.slash_access import policy_for_runner_source
  289. source = event.source
  290. policy = policy_for_runner_source(self, source)
  291. platform = source.platform.value if source and source.platform else "?"
  292. chat_type = ((source.chat_type if source else "") or "dm").lower()
  293. scope = t("gateway.whoami.scope_dm" if chat_type in {"dm", "direct", "private", ""} else "gateway.whoami.scope_group")
  294. user_id = (source.user_id if source else None) or "?"
  295. head = t("gateway.whoami.header", platform=platform, scope=scope, user_id=user_id)
  296. if not policy.enabled:
  297. return head + t("gateway.whoami.tier_unrestricted")
  298. if policy.is_admin(user_id):
  299. return head + t("gateway.whoami.tier_admin")
  300. # Non-admin: floor first (mirrors slash_access._ALWAYS_ALLOWED_FOR_USERS), then operator
  301. # additions, deduped in order.
  302. runnable = list(dict.fromkeys(["help", "whoami"] + sorted(policy.user_allowed_commands)))
  303. runnable_str = ", ".join(f"/{c}" for c in runnable) if runnable else t("gateway.shared.none_marker")
  304. return head + t("gateway.whoami.tier_user", commands=runnable_str)
  305. async def _handle_kanban_command(self, event: MessageEvent) -> str:
  306. """Handle /kanban — delegate to the shared kanban CLI (DB work in a thread pool). Allowed
  307. while an agent runs: the board is profile-agnostic and never touches agent state."""
  308. from hermes_cli.kanban import run_slash
  309. # Strip the leading "/kanban" (with or without slash), leaving args.
  310. text = (event.text or "").strip().lstrip("/")
  311. if text.startswith("kanban"):
  312. text = text[len("kanban"):].lstrip()
  313. requested_board = action = None
  314. tokens = iter(shlex.split(text) if text else [])
  315. for tok in tokens: # leading --board/--board=<b> options, then the action verb
  316. if tok == "--board":
  317. requested_board = next(tokens, requested_board)
  318. elif tok.startswith("--board="):
  319. requested_board = tok.split("=", 1)[1]
  320. else:
  321. action = tok
  322. break
  323. try:
  324. output = await asyncio.to_thread(run_slash, text)
  325. except Exception as exc: # pragma: no cover - defensive
  326. return t("gateway.kanban.error_prefix", error=exc)
  327. # Auto-subscribe on create, parsing the task id from the CLI's standard success line
  328. # ("Created t_abcd (ready, ...)"). With --json there is no such line, so a scripting user
  329. # gets no subscription and can call /kanban notify-subscribe explicitly.
  330. m = re.search(r"Created\s+(t_[0-9a-f]+)\b", output) if action == "create" and output else None
  331. if m:
  332. task_id = m.group(1)
  333. try:
  334. if await self._kanban_auto_subscribe(event, task_id, requested_board):
  335. output = output.rstrip() + "\n" + t("gateway.kanban.subscribed_suffix", task_id=task_id)
  336. except Exception as exc:
  337. logger.warning("kanban create auto-subscribe failed: %s", exc)
  338. # Gateway messages have practical length caps; truncate long listings.
  339. if len(output) > 3800:
  340. output = output[:3800] + "\n" + t("gateway.kanban.truncated_suffix")
  341. return output or t("gateway.kanban.no_output")
  342. async def _kanban_auto_subscribe(self, event: MessageEvent, task_id: str, requested_board) -> bool:
  343. """Subscribe the event's chat to *task_id* notifications (notify+wake). False when the
  344. source has no platform/chat to route back to."""
  345. source = event.source
  346. def _field(name: str) -> Optional[str]:
  347. return str(getattr(source, name, "") or "") or None
  348. platform = getattr(source, "platform", None)
  349. platform_str = (platform.value if hasattr(platform, "value") else str(platform or "")).lower()
  350. chat_id, chat_type = _field("chat_id"), _field("chat_type")
  351. delivery_metadata = self._reply_metadata(event) or None
  352. if isinstance(delivery_metadata, dict) and chat_type:
  353. delivery_metadata.setdefault("chat_type", chat_type)
  354. if not (platform_str and chat_id):
  355. return False
  356. def _sub():
  357. from hermes_cli import kanban_db as _kb
  358. from hermes_cli import kanban_db_connect as _kbc
  359. from hermes_cli import kanban_db_notify as _kbn
  360. conn = _kbc.connect(board=requested_board)
  361. try:
  362. _kbn.add_notify_sub(
  363. conn, task_id=task_id, platform=platform_str, chat_id=chat_id, chat_type=chat_type,
  364. thread_id=_field("thread_id"), user_id=_field("user_id"),
  365. # Also persist the stable alt id (Signal UUID, Feishu union_id): build_session_key
  366. # keys the participant on ``user_id_alt or user_id``, so a replayed wake rebuilds
  367. # the same session key only when the alt id survives the round-trip.
  368. user_id_alt=_field("user_id_alt"),
  369. notifier_profile=_field("profile") or getattr(self, "_kanban_notifier_profile", None) or self._active_profile_name(),
  370. # Subscribing from chat: deliver the passive message and wake the destination agent.
  371. delivery_mode="notify+wake", delivery_metadata=delivery_metadata)
  372. finally:
  373. conn.close()
  374. await asyncio.to_thread(_sub)
  375. return True
  376. async def _handle_stop_command(self, event: MessageEvent) -> str | EphemeralReply:
  377. """Handle /stop command - interrupt a running agent. A truly hung agent (blocked thread
  378. never checking _interrupt_requested) is caught by the early intercept in _handle_message();
  379. this handler runs via normal dispatch or as a fallback, and force-cleans the session lock in
  380. all cases. The session is preserved so the user can continue."""
  381. from gateway.run import _AGENT_PENDING_SENTINEL, _INTERRUPT_REASON_STOP
  382. source = event.source
  383. session_entry = await self.async_session_store.get_or_create_session(source)
  384. session_key = session_entry.session_key
  385. await self._hm_stop_owner_turn(session_key) # also between turns, before the next claim (N53)
  386. async def _stop(key: str, invalidation_reason: str) -> None:
  387. await self._interrupt_and_clear_session(
  388. key, source, interrupt_reason=_INTERRUPT_REASON_STOP,
  389. invalidation_reason=invalidation_reason)
  390. # A turn the app started while the chat was elsewhere still runs on its own key (/resume).
  391. from gateway.session_detached import chat_running_key
  392. run_key = chat_running_key(self, session_key, session_entry)
  393. agent = self._running_agents.get(run_key)
  394. if agent is _AGENT_PENDING_SENTINEL: # force-clean the sentinel so the session is unlocked
  395. await _stop(run_key, "stop_command_pending")
  396. logger.info("STOP (pending) for session %s — sentinel cleared", run_key)
  397. return EphemeralReply(t("gateway.stop.stopped_pending"))
  398. if agent: # force-clean the session lock so a truly hung agent doesn't keep it forever
  399. await _stop(run_key, "stop_command_handler")
  400. return EphemeralReply(t("gateway.stop.stopped"))
  401. # No run under the caller's own key: a live turn in THIS chat may still carry a differently
  402. # shaped key. One scan feeds both tiers; the chat tier is a superset of the thread-sibling
  403. # tier (a sibling needs the caller's own thread slot, which satisfies the chat predicate), so
  404. # it is the set to act on — acting on the sibling subset alone would reply "Stopped" while a
  405. # same-thread run under a differently shaped key kept going. See `_chat_scoped_run_keys` for
  406. # the shapes and isolation bounds; both tiers are authorization-gated.
  407. runs = self._same_chat_runs(source, session_key)
  408. sibling_keys = self._sibling_thread_run_keys(source, runs)
  409. fallback_keys = self._chat_scoped_run_keys(source, runs)
  410. # Reason is per-stop, not per-key: a stop that only ever had thread siblings keeps its own
  411. # label for hook consumers, anything wider is a chat-scope stop.
  412. reason = (
  413. "stop_command_thread_sibling"
  414. if fallback_keys == sibling_keys
  415. else "stop_command_chat_scope"
  416. )
  417. if fallback_keys and self._is_user_authorized_for_source(source):
  418. for fallback_key in fallback_keys:
  419. await _stop(fallback_key, reason)
  420. logger.info("STOP (%s) by %s — interrupted %d run(s): %s",
  421. reason, session_key, len(fallback_keys), ", ".join(fallback_keys))
  422. return EphemeralReply(t("gateway.stop.stopped"))
  423. # No running agent anywhere for this scope. Background delegations the session dispatched in an
  424. # earlier turn still count as "active": stop them; each returns as an interrupted completion.
  425. from tools.async_delegation import interrupt_for_session
  426. if interrupt_for_session(session_key=session_key, reason="stop_command",
  427. parent_session_id=str(getattr(session_entry, "session_id", "") or "")):
  428. return EphemeralReply(t("gateway.stop.stopped"))
  429. # A platform status indicator can still be stuck —
  430. # e.g. Slack's persistent assistant.threads.setStatus survives a gateway restart or a turn
  431. # that died without a final send.
  432. # Best-effort clear so /stop always dismisses a phantom "is thinking...". See #32295.
  433. adapter = getattr(self, "adapters", {}).get(source.platform)
  434. try:
  435. if adapter and hasattr(adapter, "_stop_typing_with_metadata"):
  436. await adapter._stop_typing_with_metadata(source.chat_id, self._reply_metadata(event))
  437. except Exception:
  438. logger.debug("Failed to clear typing on /stop with no active agent", exc_info=True)
  439. return t("gateway.stop.no_active")
  440. async def _handle_platform_command(self, event: MessageEvent) -> str:
  441. """Handle ``/platform list|pause|resume [name]`` — inspect and manually control failed/paused
  442. adapters (pause stops the reconnect watcher; resume re-queues for retry)."""
  443. # Strip the leading "/platform" (or "/PLATFORM") token if present
  444. parts = (getattr(event, "content", "") or "").strip().split(maxsplit=2)
  445. if parts and parts[0].lower().lstrip("/").startswith("platform"):
  446. parts = parts[1:]
  447. action = (parts[0] if parts else "list").lower()
  448. target = parts[1].lower() if len(parts) > 1 else ""
  449. failed = getattr(self, "_failed_platforms", {}) or {}
  450. if action == "list":
  451. connected = ", ".join(sorted(p.value for p in self.adapters)) or t("gateway.shared.none_marker")
  452. lines = [t("gateway.platform.header"), t("gateway.platform.connected", platforms=connected)]
  453. for p, info in failed.items():
  454. if info.get("paused"):
  455. reason = info.get("pause_reason") or t("gateway.platform.reason_default")
  456. lines.append(t("gateway.platform.item_paused", name=p.value, reason=reason))
  457. else:
  458. lines.append(t("gateway.platform.item_retrying", name=p.value, attempts=info.get("attempts", 0)))
  459. return "\n".join(lines + ([] if failed else [t("gateway.platform.none_failed")]))
  460. if action not in {"pause", "resume"}:
  461. return t("gateway.platform.usage")
  462. if not target:
  463. return t("gateway.platform.usage_action", action=action)
  464. # Resolve platform name (case-insensitive, value match)
  465. platform = next((p for p in Platform.__members__.values() if p.value.lower() == target), None)
  466. if platform is None:
  467. return t("gateway.platform.unknown", name=target)
  468. name = platform.value
  469. queued = platform in failed
  470. paused = queued and bool(failed[platform].get("paused"))
  471. if action == "pause":
  472. if not queued:
  473. return t("gateway.platform.not_queued_pause", name=name)
  474. if paused:
  475. return t("gateway.platform.already_paused", name=name)
  476. self._pause_failed_platform(platform, reason=t("gateway.platform.reason_manual"))
  477. return t("gateway.platform.paused", name=name)
  478. if not queued:
  479. return t("gateway.platform.not_queued_resume", name=name)
  480. if not paused:
  481. return t("gateway.platform.already_retrying", name=name)
  482. self._resume_paused_platform(platform)
  483. return t("gateway.platform.resumed", name=name)
  484. async def _handle_restart_command(self, event: MessageEvent) -> str | EphemeralReply:
  485. """Handle /restart command - drain active work, then restart the gateway."""
  486. from gateway.run import _hermes_home
  487. # Idempotency check: if the previous gateway process recorded this same /restart (platform +
  488. # update_id) and we see it *again*, it's a redelivery from PTB's graceful-shutdown get_updates
  489. # ACK failing on the way out. Ignoring it prevents a loop where every fresh gateway re-restarts.
  490. if self._is_stale_restart_redelivery(event):
  491. src = event.source
  492. logger.info("Ignoring redelivered /restart (platform=%s, update_id=%s) — "
  493. "already processed by a previous gateway instance.",
  494. src.platform.value if src and src.platform else "?",
  495. event.platform_update_id)
  496. return ""
  497. if self._restart_requested or self._draining:
  498. count = self._running_agent_count()
  499. return t("gateway.draining", count=count) if count else EphemeralReply(t("gateway.restart.in_progress"))
  500. async def _write_marker(name: str, build, label: str) -> None:
  501. try:
  502. await asyncio.to_thread(atomic_json_write, _hermes_home / name, build(), indent=None)
  503. except Exception as e:
  504. logger.debug("Failed to write restart %s: %s", label, e)
  505. def _notify_payload() -> dict:
  506. data = _restart_notify_payload(event)
  507. mid = str(event.message_id) if event.message_id is not None else event.source.message_id
  508. try:
  509. self._restart_command_source = dataclasses.replace(event.source, message_id=mid)
  510. except Exception:
  511. self._restart_command_source = event.source
  512. return data
  513. def _dedup_payload() -> dict:
  514. # Platform + update_id of the triggering /restart, for redelivery detection.
  515. data = {"platform": event.source.platform.value if event.source.platform else None,
  516. "requested_at": time.time()}
  517. if event.platform_update_id is not None:
  518. data["update_id"] = event.platform_update_id
  519. return data
  520. # Save the requester's routing info so the new gateway process can notify them once back.
  521. await _write_marker(".restart_notify.json", _notify_payload, "notify file")
  522. # Record the triggering platform + update_id in a dedicated dedup marker. Unlike
  523. # .restart_notify.json (unlinked once the new gateway sends its notification) this persists
  524. # so a delayed Telegram redelivery is still detectable. Overwritten on every /restart.
  525. await _write_marker(".restart_last_processed.json", _dedup_payload, "dedup marker")
  526. active_agents = self._running_agent_count()
  527. # Under a service manager (systemd/launchd) or Docker/Podman, exit 75 so the supervisor /
  528. # restart policy restarts us — detached setsid+bash fails there (systemd KillMode=mixed kills
  529. # the cgroup; tini exits with the gateway). The explicit marker covers ``sudo env -i`` wrappers.
  530. from gateway.restart import is_container_restart_context, is_gateway_supervisor_process
  531. via_service = is_gateway_supervisor_process() or is_container_restart_context()
  532. self.request_restart(detached=not via_service, via_service=via_service)
  533. # Track sessions that were active at shutdown for stuck-loop detection (#7536). On each restart, the
  534. # counter increments for sessions that were running. If a session hits the threshold (3 consecutive
  535. # restarts while active), the next startup auto-suspends it — breaking the loop.
  536. if active_agents:
  537. return t("gateway.draining", count=active_agents)
  538. return EphemeralReply(t("gateway.restart.restarting"))
  539. async def _handle_autoprune_command(self, event: MessageEvent) -> str:
  540. """Handle /autoprune — the low-disk auto-prune decision (same text as the CLI)."""
  541. from hermes_cli.prune_advisor import answered
  542. reply = _execute("autoprune", args=event.get_command_args()).text
  543. if event.get_command_args().strip() and answered(): # a failed save or `status` keeps it
  544. from gateway.run_housekeeping_disk import clear_local_auto_prune_notice
  545. clear_local_auto_prune_notice(self, event.source)
  546. return reply
  547. async def _handle_version_command(self, event: MessageEvent) -> str:
  548. """Handle /version — show the running Hermes Agent version."""
  549. return _execute("version").text
  550. def _catalog_options(self, event: MessageEvent) -> dict:
  551. """``allowed_commands`` for /help and /commands when the caller is a gated non-admin:
  552. the slash-access floor + ``user_allowed_commands`` (mirrors /whoami), so the catalog
  553. never advertises commands ``_check_slash_access`` would refuse. Admins / ungated -> {}."""
  554. from gateway.slash_access import policy_for_runner_source
  555. source = event.source
  556. # Partially-constructed runners (``GatewayRunner.__new__`` in tests) have no ``config``;
  557. # policy_for_source treats None as ungated.
  558. policy = policy_for_runner_source(self, source)
  559. if policy.enabled and not policy.is_admin(source.user_id if source else None):
  560. return {"allowed_commands": {"help", "whoami", *policy.user_allowed_commands}}
  561. return {}
  562. async def _handle_help_command(self, event: MessageEvent) -> str:
  563. """Handle /help command - list available commands."""
  564. return self._telegramized_command_reply(
  565. event, _execute("help", options=self._catalog_options(event)).text)
  566. async def _handle_commands_command(self, event: MessageEvent) -> str:
  567. # Page size is a surface parameter (Telegram messages are shorter).
  568. page_size = 15 if event.source.platform == Platform.TELEGRAM else 20
  569. options = {"page_size": page_size, **self._catalog_options(event)}
  570. reply = _execute("commands", args=event.get_command_args(), options=options)
  571. return self._telegramized_command_reply(event, reply.text)
  572. async def _handle_set_home_command(self, event: MessageEvent) -> str:
  573. """Handle /sethome command -- set the current chat as the platform's home channel."""
  574. from gateway.run import _home_target_env_var, _home_thread_env_var
  575. source = event.source
  576. platform_name = source.platform.value if source.platform else "unknown"
  577. chat_id = source.chat_id
  578. chat_name = source.chat_name or chat_id
  579. if source.platform is None:
  580. return t("gateway.set_home.save_failed", error=t("gateway.set_home.err_missing_platform"))
  581. via_relay = getattr(source, "delivered_via_upstream_relay", False) is True
  582. if via_relay:
  583. adapter_for_source = getattr(self, "_intake_adapter_for", None)
  584. relay_adapter = adapter_for_source(source) if callable(adapter_for_source) else None
  585. fronts_platform = getattr(relay_adapter, "fronts_platform", None)
  586. if (source.platform in {None, Platform.LOCAL, Platform.RELAY}
  587. or not getattr(source, "user_id", None)
  588. or not callable(fronts_platform) or not fronts_platform(source.platform)):
  589. return t("gateway.set_home.save_failed", error=t("gateway.set_home.err_relay_unauthenticated"))
  590. thread_id = _home_thread_from_source(source)
  591. home = HomeChannel(
  592. platform=source.platform, chat_id=str(chat_id), name=chat_name, thread_id=thread_id,
  593. user_id=str(source.user_id) if getattr(source, "user_id", None) else None,
  594. scope_id=str(source.scope_id) if getattr(source, "scope_id", None) else None)
  595. # config.yaml is canonical because it can persist the authenticated logical-target
  596. # provenance required by Relay after a restart.
  597. try:
  598. persist_home_channel(home, enabled_if_new=not via_relay)
  599. except Exception as e:
  600. return t("gateway.set_home.save_failed", error=e)
  601. # Preserve legacy home env vars for existing cron/setup consumers.
  602. try:
  603. from hermes_cli.config import save_env_value
  604. save_env_value(_home_target_env_var(platform_name), str(chat_id))
  605. save_env_value(_home_thread_env_var(platform_name), str(thread_id or ""))
  606. except Exception as e:
  607. logger.warning("Home config saved but legacy env persistence failed: %s", e)
  608. # Keep the running gateway config in sync too. The pre-restart notification path reads
  609. # self.config before the process reloads config.
  610. platform_config = self.config.platforms.setdefault(source.platform, PlatformConfig(enabled=not via_relay))
  611. platform_config.home_channel = home
  612. return t("gateway.set_home.success", name=chat_name, chat_id=chat_id)
  613. async def _handle_voice_command(self, event: MessageEvent) -> str:
  614. """Handle /voice [on|off|tts|channel|leave|status] command."""
  615. args = event.get_command_args().strip().lower()
  616. chat_id = event.source.chat_id
  617. # Voice state belongs to the (bot, chat) pair: resolve the adapter that received the
  618. # command and key the mode by its owning profile so two multiplexed bots in one chat keep
  619. # independent /voice state.
  620. # See #75198.
  621. voice_key = self._voice_key_for_source(event.source)
  622. adapter = self._delivery_adapter_for(event.source)
  623. def _set_mode(mode: str) -> None:
  624. self._voice_mode[voice_key] = mode
  625. self._save_voice_modes()
  626. from gateway.session_config import local_voice_transition
  627. local_voice_transition(event.source, mode)
  628. if not adapter:
  629. return
  630. if mode == "off":
  631. self._set_adapter_auto_tts_disabled(adapter, chat_id, disabled=True)
  632. else:
  633. self._set_adapter_auto_tts_enabled(adapter, chat_id, enabled=True)
  634. if args in _VOICE_MODE_BY_ARG:
  635. mode, reply_key = _VOICE_MODE_BY_ARG[args]
  636. _set_mode(mode)
  637. return t(reply_key)
  638. if args in {"channel", "join"}:
  639. return await self._handle_voice_channel_join(event)
  640. if args == "leave":
  641. return await self._handle_voice_channel_leave(event)
  642. if args == "status":
  643. mode = self._voice_mode.get(voice_key, "off")
  644. label = t(f"gateway.voice.label_{mode}") if mode in ("off", "voice_only", "all") else mode
  645. lines = [t("gateway.voice.status_mode", label=label)]
  646. guild_id = self._get_guild_id(event) # append voice channel info if connected
  647. info = adapter.get_voice_channel_info(guild_id) if guild_id and hasattr(adapter, "get_voice_channel_info") else None
  648. if info:
  649. lines += [t("gateway.voice.status_channel", channel=info['channel_name']),
  650. t("gateway.voice.status_participants", count=info['member_count'])]
  651. for m in info["members"]:
  652. status = t("gateway.voice.speaking") if m.get("is_speaking") else ""
  653. lines.append(t("gateway.voice.status_member", name=m['display_name'], status=status))
  654. return "\n".join(lines)
  655. # Toggle: off → on, on/all → off
  656. turning_on = self._voice_mode.get(voice_key, "off") == "off"
  657. _set_mode("voice_only" if turning_on else "off")
  658. toggle_line = t("gateway.voice.enabled_short" if turning_on else "gateway.voice.disabled_short")
  659. # Bare /voice still toggles, but append an explainer so users discover the on/off/tts/status
  660. # subcommands (and, on Discord, live voice-channel join/leave). Toggle result shows first.
  661. supports_voice_channels = adapter is not None and hasattr(adapter, "join_voice_channel")
  662. channels = t("gateway.voice.help_channels") if supports_voice_channels else ""
  663. return t("gateway.voice.help", toggle=toggle_line, channels=channels)
  664. async def _handle_rollback_command(self, event: MessageEvent) -> str:
  665. """Handle /rollback command — list or restore filesystem checkpoints."""
  666. from tools.checkpoint_manager import format_checkpoint_list
  667. mgr = self._checkpoint_manager(event.source)
  668. if mgr is None:
  669. return t("gateway.rollback.not_enabled")
  670. cwd = self._terminal_cwd()
  671. # --all / --force: classic full restore, overwriting user edits too.
  672. tokens = event.get_command_args().strip().split()
  673. restore_all = any(tok.lower() in ("--all", "--force") for tok in tokens)
  674. arg = " ".join(tok for tok in tokens if tok.lower() not in ("--all", "--force"))
  675. # Container-backed session: host checkpoints belong to another tree, so a restore is
  676. # refused; the bare listing stays visible, prefixed with the reason (same as the CLI).
  677. reason = mgr.unsupported_backend_reason()
  678. if reason and arg:
  679. return reason
  680. checkpoints = mgr.list_checkpoints(cwd)
  681. if not arg:
  682. listing = format_checkpoint_list(checkpoints, cwd)
  683. return f"{reason}\n{listing}" if reason else listing
  684. if not checkpoints:
  685. return t("gateway.rollback.none_found", cwd=cwd)
  686. # Restore by number or hash
  687. try:
  688. idx = int(arg) - 1
  689. except ValueError:
  690. target_hash = arg
  691. else:
  692. if not 0 <= idx < len(checkpoints):
  693. return t("gateway.rollback.invalid_number", max=len(checkpoints))
  694. target_hash = checkpoints[idx]["hash"]
  695. result = mgr.restore(cwd, target_hash, safe=not restore_all)
  696. if not result["success"]:
  697. return t("gateway.rollback.restore_failed", error=result["error"])
  698. msg = t("gateway.rollback.restored", hash=result["restored_to"], reason=result["reason"])
  699. for result_key, i18n_key in _ROLLBACK_SKIP_LINES:
  700. files = result.get(result_key) or []
  701. if files:
  702. more = f" (+{len(files) - 5})" if len(files) > 5 else ""
  703. msg += "\n" + t(i18n_key, files=", ".join(files[:5]) + more)
  704. return msg
  705. async def _handle_diff_command(self, event: MessageEvent) -> str:
  706. """Handle /diff — show git changes in the working directory. Diff body is truncated hard
  707. here (chat is not a pager); platform senders clamp further."""
  708. args = [a.lower() for a in event.get_command_args().strip().split()]
  709. stat_only = bool({"--stat", "stat"} & set(args))
  710. mode = "working"
  711. for low in args:
  712. mode = _DIFF_MODE_BY_ARG.get(low, mode)
  713. cwd = self._terminal_cwd()
  714. if mode == "session":
  715. # Cumulative checkpoint-baseline diff.
  716. mgr = self._checkpoint_manager(event.source)
  717. if mgr is None:
  718. return t("gateway.diff.not_enabled")
  719. if reason := mgr.unsupported_backend_reason(): # host baseline is not this session's tree
  720. return reason
  721. result = await asyncio.to_thread(mgr.session_diff, cwd)
  722. else:
  723. from tools.working_diff import collect_working_diff
  724. result = await asyncio.to_thread(collect_working_diff, cwd, mode)
  725. if not result.get("success"):
  726. return t("gateway.diff.failed", error=result.get("error") or t("gateway.diff.err_default"))
  727. return self._render_diff_result(result, stat_only)
  728. def _render_diff_result(self, result: dict, stat_only: bool) -> str:
  729. """Render a working/session diff result: stat block, untracked list, fenced (truncated) diff."""
  730. stat = result.get("stat", "")
  731. diff = result.get("diff", "")
  732. untracked = result.get("untracked", [])
  733. if result.get("empty") or (not stat and not diff and not untracked):
  734. return t("gateway.diff.no_changes")
  735. out: list[str] = []
  736. if stat:
  737. out.append(f"```\n{stat}\n```")
  738. if untracked:
  739. shown = "\n".join(f"+ {rel}" for rel in untracked[:15])
  740. more = t("gateway.diff.more_untracked", count=len(untracked) - 15) if len(untracked) > 15 else ""
  741. out.append(f"{t('gateway.diff.untracked_label')}\n```\n{shown}{more}\n```")
  742. if not stat_only and diff:
  743. out.append(self._fenced_truncated_diff(diff))
  744. return "\n\n".join(out)
  745. @staticmethod
  746. def _fenced_truncated_diff(diff: str, max_lines: int = 60, max_chars: int = 3000) -> str:
  747. """Fence a diff body, truncating to messaging-friendly size."""
  748. diff_lines = diff.splitlines()
  749. truncated = len(diff_lines) > max_lines
  750. if truncated:
  751. diff = "\n".join(diff_lines[:max_lines])
  752. if len(diff) > max_chars:
  753. diff = diff[:max_chars]
  754. truncated = True
  755. note = ""
  756. if truncated:
  757. note = t("gateway.diff.truncated_note", lines=len(diff_lines))
  758. return f"```diff\n{diff}{note}\n```"
  759. def _track_background_task(self, coro) -> None:
  760. """Fire-and-forget *coro*, keeping a strong ref in ``_background_tasks`` until it finishes."""
  761. task = asyncio.create_task(coro)
  762. self._background_tasks.add(task)
  763. task.add_done_callback(self._background_tasks.discard)
  764. async def _handle_background_command(self, event: MessageEvent) -> str:
  765. """Handle /bg <prompt> — run a prompt in a background thread with its own session; the
  766. result is sent to the same chat without touching the active session's history."""
  767. prompt = event.get_command_args().strip()
  768. if not prompt:
  769. return t("gateway.background.usage")
  770. task_id = f"bg_{datetime.now().strftime('%H%M%S')}_{os.urandom(3).hex()}"
  771. self._track_background_task(self._run_background_task(
  772. prompt, event.source, task_id, event_message_id=self._reply_anchor_for_event(event),
  773. # Forward image/audio attachments so the background agent can see them.
  774. media_urls=list(event.media_urls or []), media_types=list(event.media_types or [])))
  775. return t("gateway.background.started", preview=_preview(prompt), task_id=task_id)
  776. async def _handle_btw_command(self, event: MessageEvent) -> str:
  777. """Handle /btw <question> — one-shot auxiliary LLM call on a transcript snapshot; live history
  778. is never touched (alternation + prompt cache intact, current turn keeps running). Unlike /bg,
  779. which spawns a fresh contextless session."""
  780. question = event.get_command_args().strip()
  781. if not question:
  782. return t("gateway.btw.usage")
  783. source = event.source
  784. session_entry = await self.async_session_store.get_or_create_session(source)
  785. try:
  786. history = await self.async_session_store.load_transcript(session_entry.session_id)
  787. except TranscriptReadError:
  788. return history_unreadable()
  789. if not history:
  790. return t("gateway.btw.no_history")
  791. try:
  792. model, rt = self._resolve_session_agent_runtime(source=source)
  793. except Exception:
  794. model, rt = None, {}
  795. if not rt.get("api_key"):
  796. return t("gateway.btw.no_provider")
  797. main_runtime = {
  798. "model": model,
  799. **{k: rt.get(k) for k in ("provider", "base_url", "api_key", "api_mode")},
  800. "session_id": session_entry.session_id,
  801. }
  802. history_snapshot = list(history)
  803. # Prefer the cache-parity fork when a live cached AIAgent exists: it replays the snapshot
  804. # against the warm provider prefix cache, giving FULL context at cache-read prices. With no
  805. # cached agent the cache is cold anyway — answer_side_question's digest fallback handles it.
  806. try:
  807. parent_agent = self._cached_agent_for(self._session_key_for_source(source))
  808. except Exception:
  809. parent_agent = None
  810. _thread_metadata = self._reply_metadata(event)
  811. adapter = self._delivery_adapter_for(source)
  812. preview = _preview(question)
  813. async def _run_side_question() -> None:
  814. from agent.side_question import answer_side_question
  815. try:
  816. answer = await asyncio.to_thread(
  817. answer_side_question, question, history_snapshot,
  818. parent_agent=parent_agent, main_runtime=main_runtime)
  819. reply = t("gateway.btw.answer", preview=preview, answer=answer or "")
  820. except Exception as e:
  821. logger.warning("/btw side question failed: %s", e)
  822. reply = t("gateway.btw.failed", preview=preview, error=str(e))
  823. if adapter is not None:
  824. await adapter.send(source.chat_id, reply, metadata=_thread_metadata)
  825. self._track_background_task(_run_side_question())
  826. return t("gateway.btw.started", preview=preview)
  827. async def _handle_memory_command(self, event: MessageEvent) -> str:
  828. """Handle /memory — review pending memory writes + toggle the approval gate. Entries are small
  829. enough to review inline, so the full flow works on every platform."""
  830. from hermes_cli.write_approval_commands import handle_pending_subcommand
  831. from tools import write_approval as wa
  832. from tools.memory_tool import load_on_disk_store
  833. # Apply approved writes against a fresh on-disk store (the gateway has no long-lived agent;
  834. # the store persists to the same MEMORY/USER.md and honors the configured char limits).
  835. out = handle_pending_subcommand(
  836. wa.MEMORY, event.get_command_args().strip().split(), memory_store=load_on_disk_store(),
  837. set_mode_fn=self._write_approval_setter("memory", event))
  838. return out if out is not None else t("gateway.memory.unknown_subcommand")
  839. async def _handle_skills_command(self, event: MessageEvent) -> str:
  840. """Handle /skills on the gateway — pending skill-write review only (hub stays CLI-only). Gated
  841. by ``skills.write_approval`` but still answers when staged writes exist after the gate is off
  842. (never stranded). ``diff`` is truncated for chat."""
  843. from hermes_cli.write_approval_commands import handle_pending_subcommand
  844. from tools import write_approval as wa
  845. args = event.get_command_args().strip().split()
  846. sub = args[0].lower() if args else ""
  847. gate_off = not wa.write_approval_enabled(wa.SKILLS) and sub not in {"approval", "mode"}
  848. if gate_off and wa.pending_count(wa.SKILLS) == 0:
  849. return t("gateway.skills.gate_off")
  850. out = handle_pending_subcommand(
  851. wa.SKILLS, args, set_mode_fn=self._write_approval_setter("skills", event))
  852. if out is None:
  853. return t("gateway.skills.unknown_subcommand")
  854. # Chat bubbles can't hold a full skill diff — truncate and point at the pending JSON file
  855. # (NOT `hermes skills diff <name>`, which diffs a bundled skill against its stock version).
  856. if sub == "diff" and len(out) > 3000:
  857. pending_id = args[1] if len(args) > 1 else "<id>"
  858. out = out[:3000] + t("gateway.skills.diff_truncated", pending_id=pending_id)
  859. return out
  860. async def _handle_approvals_command(self, event: MessageEvent) -> str:
  861. """Show or persist the profile-wide dangerous-command approval mode."""
  862. from gateway.slash_access import policy_for_runner_source
  863. from hermes_cli.approval_mode import run_approval_mode_command
  864. requested = event.get_command_args().strip() or None
  865. # This mutates profile-wide security policy. The central slash gate can allow selected
  866. # commands to non-admin users, so enforce admin again at this side-effect boundary.
  867. # Unconfigured policies remain unrestricted.
  868. policy = policy_for_runner_source(self, event.source)
  869. if requested and not policy.is_admin(event.source.user_id):
  870. return t("gateway.approvals.admin_only")
  871. # Approval checks load config dynamically; do not evict the cached agent or alter its
  872. # system prompt/tool schema (prompt-cache prefix is sacred).
  873. return run_approval_mode_command(requested).message
  874. async def _handle_yolo_command(self, event: MessageEvent) -> str | EphemeralReply:
  875. """Handle /yolo — toggle dangerous command approval bypass for this session only. The flag is
  876. persisted on the routing entry so it survives a gateway restart."""
  877. from tools.approval_yolo import toggle_session_yolo
  878. session_key = self._session_key_for_source(event.source)
  879. persisted, persist = False, None
  880. if (store := self.session_store) is not None:
  881. # A first-message /yolo has no routing entry yet; materialize it so the flag has a home.
  882. persisted = (await self.async_session_store.get_or_create_session(event.source)).yolo is True
  883. persist = lambda on: store.set_session_yolo(session_key, on)
  884. # Off the loop: the persist is a routing-store write (thread-safe, like AsyncSessionStore's calls).
  885. enable = await asyncio.to_thread(toggle_session_yolo, session_key, persisted=persisted, persist=persist)
  886. return EphemeralReply(t("gateway.yolo.enabled" if enable else "gateway.yolo.disabled"))
  887. async def _handle_verbose_command(self, event: MessageEvent) -> str:
  888. """Handle /verbose — cycle tool progress display mode (off → new → all → verbose → log) per
  889. *current platform*, saved to ``display.platforms.<platform>.tool_progress``. Gated by
  890. ``display.tool_progress_command`` (default off)."""
  891. from gateway.run import _load_gateway_config
  892. from gateway.session_setting_commands import local_live
  893. config_path, platform_key = self._display_config_target(event)
  894. live = local_live(self, event.source)
  895. try:
  896. user_config = _load_gateway_config()
  897. gate_enabled = is_truthy_value(cfg_get(user_config, "display", "tool_progress_command"),
  898. default=False)
  899. except Exception:
  900. user_config, gate_enabled = {}, False
  901. # The opt-in gate is for messaging chats; a local session always owned /verbose.
  902. if not gate_enabled and live is None:
  903. return t("gateway.verbose.not_enabled")
  904. # Cycle mode (per-platform), reading the current effective mode via the resolver. ``log``
  905. # (tool calls to a log file instead of the chat) is a messaging mode: a local client renders
  906. # every tool event itself.
  907. from gateway.display_config import resolve_display_setting
  908. cycle = ["off", "new", "all", "verbose"] + ([] if live is not None else ["log"])
  909. current = (getattr(live, "tool_progress_mode", None) if live is not None else None) or \
  910. resolve_display_setting(user_config, platform_key, "tool_progress", "all")
  911. new_mode = cycle[(cycle.index(current if current in cycle else "all") + 1) % len(cycle)]
  912. if live is not None:
  913. live.tool_progress_mode = new_mode # what ``config.get verbose`` and the next tool event read
  914. description = t(f"gateway.verbose.mode_{new_mode}")
  915. try:
  916. _write_raw_config_leaf(config_path, ("display", "platforms", platform_key, "tool_progress"), new_mode)
  917. return f"{description}\n" + t("gateway.verbose.saved_suffix", platform=platform_key)
  918. except Exception as e:
  919. logger.warning("Failed to save tool_progress mode: %s", e)
  920. return f"{description}\n" + t("gateway.verbose.save_failed", error=e)
  921. async def _handle_busy_command(self, event: MessageEvent) -> str | EphemeralReply:
  922. """Handle /busy — control what happens when messaging while Hermes is working."""
  923. from gateway.session_setting_commands import local_live, session_busy_mode
  924. arg = event.get_command_args().strip().lower()
  925. live = local_live(self, event.source)
  926. if not arg or arg == "status":
  927. mode = session_busy_mode(self, live) if live is not None else self._effective_busy_input_mode(event.source)
  928. behavior = t(_BUSY_MODE_BEHAVIOR.get(mode, _BUSY_MODE_BEHAVIOR["interrupt"])[0])
  929. return EphemeralReply(t("gateway.busy.status", mode=mode, behavior=behavior))
  930. if arg not in _BUSY_MODE_BEHAVIOR:
  931. return EphemeralReply(t("gateway.busy.unknown_mode", arg=arg))
  932. # Persist before mutate
  933. from cli import save_config_value
  934. if not save_config_value("display.busy_input_mode", arg):
  935. return EphemeralReply(t("gateway.busy.save_failed"))
  936. if live is not None:
  937. live.busy_input_mode = arg # the frozen session does not re-read config.yaml
  938. profile_name = self._busy_profile_name_for_source(event.source)
  939. if profile_name:
  940. from gateway.run import _load_gateway_config
  941. self._snapshot_profile_busy_modes(profile_name, _load_gateway_config())
  942. else:
  943. self._busy_input_mode = arg
  944. # busy_input_mode is also the source of truth for the text mode — re-derive it so the
  945. # adapter refresh below doesn't keep a stale value and keep interrupting.
  946. self._busy_text_mode = self._load_busy_text_mode()
  947. adapter = self._delivery_adapter_for(event.source)
  948. if adapter is not None:
  949. adapter._busy_text_mode = self._effective_busy_text_mode(event.source)
  950. return EphemeralReply(t("gateway.busy.set", mode=arg, behavior=t(_BUSY_MODE_BEHAVIOR[arg][1])))
  951. async def _handle_footer_command(self, event: MessageEvent) -> str:
  952. """Handle /footer command — toggle the runtime-metadata footer."""
  953. from gateway.run import _load_gateway_config, _resolve_gateway_model
  954. from gateway.runtime_footer import format_runtime_footer, resolve_footer_config
  955. config_path, platform_key = self._display_config_target(event)
  956. arg = event.get_command_args().strip().lower()
  957. try:
  958. user_config: dict = _load_gateway_config()
  959. except Exception as e:
  960. return t("gateway.config_read_failed", error=e)
  961. effective = resolve_footer_config(user_config, platform_key)
  962. def _state(enabled: bool) -> str:
  963. return t("gateway.footer.state_on") if enabled else t("gateway.footer.state_off")
  964. if arg in {"status", "?"}:
  965. return t("gateway.footer.status", state=_state(effective["enabled"]),
  966. fields=", ".join(effective.get("fields") or []), platform=platform_key)
  967. if arg and arg not in _FOOTER_STATE_BY_ARG:
  968. return t("gateway.footer.usage")
  969. new_state = _FOOTER_STATE_BY_ARG[arg] if arg else not effective["enabled"]
  970. try:
  971. # A local session writes the ``cli`` key, as /reasoning show|hide saves: every local
  972. # surface reads it (gateway.display_config.local_display_config), so the setting holds
  973. # wherever it was set (T7). A chat's /footer keeps the global key it always wrote.
  974. leaf = (("display", "platforms", platform_key) if event.source.platform == Platform.LOCAL
  975. else ("display",)) + ("runtime_footer", "enabled")
  976. _write_raw_config_leaf(config_path, leaf, new_state)
  977. except Exception as e:
  978. logger.warning("Failed to save runtime_footer.enabled: %s", e)
  979. return t("gateway.config_save_failed", error=e)
  980. example = ""
  981. if new_state:
  982. # Show a preview using current agent state if available.
  983. preview = format_runtime_footer(
  984. model=_resolve_gateway_model(user_config) or None, context_tokens=0, context_length=None,
  985. fields=effective.get("fields") or ["model", "context_pct", "cwd"])
  986. if preview:
  987. example = t("gateway.footer.example_line", preview=preview)
  988. return t("gateway.footer.saved", state=_state(new_state), example=example)
  989. async def _handle_reload_mcp_command(self, event: MessageEvent) -> Optional[str]:
  990. """Handle /reload-mcp — reconnect MCP servers and rebuild the cached agent. Reloading
  991. invalidates the provider prompt cache (tool schemas live in the system prompt), so it routes
  992. through slash-confirm; "Always Approve" persists ``approvals.mcp_reload_confirm: false``."""
  993. session_key = self._session_key_for_source(event.source)
  994. # Read the gate fresh from disk so a prior "always" click takes effect on the next
  995. # invocation without restarting the gateway.
  996. user_config = self._read_user_config()
  997. approvals = user_config.get("approvals") if isinstance(user_config, dict) else None
  998. if isinstance(approvals, dict) and not approvals.get("mcp_reload_confirm", True):
  999. return await self._execute_mcp_reload(event)
  1000. # Route through slash-confirm. The primitive sends the prompt and stores the resume handler;
  1001. # the button/text response triggers ``_resolve_slash_confirm`` which invokes the handler
  1002. # with the chosen outcome.
  1003. async def _on_confirm(choice: str) -> Optional[str]:
  1004. if choice == "cancel":
  1005. return t("gateway.reload_mcp.cancelled")
  1006. if choice == "always":
  1007. # Persist the opt-out and run the reload.
  1008. try:
  1009. from cli import save_config_value
  1010. save_config_value("approvals.mcp_reload_confirm", False)
  1011. logger.info("User opted out of /reload-mcp confirmation (session=%s)", session_key)
  1012. except Exception as exc:
  1013. logger.warning("Failed to persist mcp_reload_confirm=false: %s", exc)
  1014. # once / always → run the reload
  1015. result = await self._execute_mcp_reload(event)
  1016. if choice == "always":
  1017. return f"{result}\n\n" + t("gateway.reload_mcp.always_followup")
  1018. return result
  1019. return await self._request_slash_confirm(
  1020. event=event, command="reload-mcp", title="/reload-mcp",
  1021. message=t("gateway.reload_mcp.confirm_prompt"), handler=_on_confirm)
  1022. async def _handle_reload_skills_command(self, event: MessageEvent) -> str:
  1023. """Handle /reload-skills — rescan skills dir, queue a note for next turn. Skills are invoked at
  1024. runtime, not baked into the system prompt, so this does NOT clear the prompt cache. The diff
  1025. goes into ``_pending_skills_reload_notes[session_key]``, prepended to the NEXT user message —
  1026. nothing out-of-band, so alternation is preserved."""
  1027. try:
  1028. from agent.skill_commands import reload_skills
  1029. # _run_in_executor_with_context, not a bare hop: the rescan walks
  1030. # get_hermes_home()/skills, a contextvar override under multiplex.
  1031. result = await self._run_in_executor_with_context(reload_skills)
  1032. added, removed = result.get("added", []), result.get("removed", []) # [{"name", "description"}]
  1033. total = result.get("total", 0)
  1034. # Let adapters refresh platform-side state that cached the skill list at startup (today:
  1035. # Discord /skill autocomplete — otherwise new skills stay invisible and deleted ones
  1036. # error). Adapters without refresh_skill_group are skipped; the in-process reload suffices.
  1037. for adapter in list(self.adapters.values()):
  1038. refresh = getattr(adapter, "refresh_skill_group", None)
  1039. try:
  1040. maybe = refresh() if callable(refresh) else None
  1041. if inspect.isawaitable(maybe):
  1042. await maybe
  1043. except Exception as exc:
  1044. logger.warning("Adapter %s refresh_skill_group raised: %s",
  1045. getattr(adapter, "name", adapter), exc)
  1046. lines = [t("gateway.reload_skills.header")]
  1047. if not added and not removed:
  1048. lines += [t("gateway.reload_skills.no_new"), t("gateway.reload_skills.total", count=total)]
  1049. return "\n".join(lines)
  1050. def _fmt_line(item: dict) -> str:
  1051. nm, desc = item.get("name", ""), item.get("description", "")
  1052. return (t("gateway.reload_skills.item_with_desc", name=nm, desc=desc) if desc
  1053. else t("gateway.reload_skills.item_no_desc", name=nm))
  1054. # Queue a one-shot note for the next user turn in this session too. Format matches how
  1055. # the system prompt renders pre-existing skills (`` - name: description``) so the
  1056. # model reads the diff in the same shape as its original skill catalog.
  1057. sections = ["[USER INITIATED SKILLS RELOAD:"]
  1058. for i18n_key, note_header, items in (
  1059. ("gateway.reload_skills.added_header", "Added Skills:", added),
  1060. ("gateway.reload_skills.removed_header", "Removed Skills:", removed)):
  1061. if items:
  1062. formatted = [_fmt_line(item) for item in items]
  1063. lines += [t(i18n_key)] + formatted
  1064. sections += ["", note_header] + formatted
  1065. lines.append(t("gateway.reload_skills.total", count=total))
  1066. sections += ["", "Use skills_list to see the updated catalog.]"]
  1067. session_key = self._session_key_for_source(event.source)
  1068. if not hasattr(self, "_pending_skills_reload_notes"):
  1069. self._pending_skills_reload_notes = {}
  1070. if session_key:
  1071. self._pending_skills_reload_notes[session_key] = "\n".join(sections)
  1072. return "\n".join(lines)
  1073. except Exception as e:
  1074. logger.warning("Skills reload failed: %s", e)
  1075. return t("gateway.reload_skills.failed", error=e)
  1076. async def _handle_bundles_command(self, event: MessageEvent) -> str:
  1077. """Handle /bundles — list installed skill bundles (mirrors the CLI handler). Bundles are
  1078. loaded by invoking their own ``/<slug>`` command, not by this one."""
  1079. reply = _execute("bundles")
  1080. if "error" in reply.data:
  1081. logger.warning("Bundles command unavailable: %s", reply.data["error"])
  1082. return reply.text
  1083. bundles = reply.data["bundles"]
  1084. if not bundles:
  1085. return t("gateway.bundles.none", dir=reply.data["dir"])
  1086. lines = [t("gateway.bundles.header", count=len(bundles)), ""]
  1087. for info in bundles:
  1088. skills = info.get("skills", [])
  1089. desc = info.get("description") or t("gateway.bundles.default_desc", count=len(skills))
  1090. lines += [t("gateway.bundles.item", slug=info["slug"], desc=desc, count=len(skills))] + [f" · {s}" for s in skills]
  1091. return "\n".join(lines + ["", t("gateway.bundles.invoke_hint")])
  1092. def _blocking_approval_or_stale(self, event: MessageEvent, stale_key: str, none_key: str):
  1093. """``(session_key, None)`` when an agent thread is blocked on approval, else the reply to send.
  1094. A pending-approvals entry with no blocked thread is a stale prompt: drop it and say so."""
  1095. from tools.approval import has_blocking_approval
  1096. session_key = self._session_key_for_source(event.source)
  1097. if has_blocking_approval(session_key):
  1098. return session_key, None
  1099. if session_key in self._pending_approvals:
  1100. self._pending_approvals.pop(session_key)
  1101. return session_key, t(stale_key)
  1102. return session_key, t(none_key)
  1103. async def _handle_approve_command(self, event: MessageEvent) -> Optional[str]:
  1104. """Handle /approve — unblock waiting agent thread(s). They block inside tools/approval.py;
  1105. signalling the event resumes them so the command executes inline (same flow as the CLI)."""
  1106. from tools.approval import resolve_gateway_approval
  1107. session_key, stale = self._blocking_approval_or_stale(event, "gateway.approval_expired",
  1108. "gateway.approve.no_pending")
  1109. if stale:
  1110. return stale
  1111. # Args: "all", "all session", "all always", "session", "always" ("always" beats "session").
  1112. args = event.get_command_args().strip().lower().split()
  1113. choices = {_APPROVE_CHOICE_BY_ARG[a] for a in args if a in _APPROVE_CHOICE_BY_ARG}
  1114. choice = "always" if "always" in choices else "session" if "session" in choices else "once"
  1115. count = resolve_gateway_approval(session_key, choice, resolve_all="all" in args)
  1116. if not count:
  1117. return t("gateway.approve.no_pending")
  1118. confirmation_text = t(f"gateway.approve.{choice}_{'plural' if count > 1 else 'singular'}", count=count)
  1119. logger.info("User approved %d dangerous command(s) via /approve (%s)", count, choice)
  1120. return await self._deliver_approval_confirmation(event, confirmation_text, "approve")
  1121. async def _handle_deny_command(self, event: MessageEvent) -> str:
  1122. """Handle /deny — reject pending dangerous command(s) with a definitive BLOCKED result, as in
  1123. the CLI. ``/deny`` denies the oldest; ``/deny all`` denies everything.
  1124. ``/deny <reason>`` (or ``/deny all <reason>``) attaches a one-line reason that is relayed back to
  1125. the agent so it can adapt instead of only hearing "denied". Ported from qwibitai/nanoclaw#2832.
  1126. """
  1127. from tools.approval import resolve_gateway_approval
  1128. session_key, stale = self._blocking_approval_or_stale(event, "gateway.deny.stale",
  1129. "gateway.deny.no_pending")
  1130. if stale:
  1131. return stale
  1132. # A leading "all" denies every pending command; the rest (or the whole arg string without
  1133. # "all") is the optional deny reason relayed to the agent, capped to a sane one-liner.
  1134. raw_args = event.get_command_args().strip()
  1135. tokens = raw_args.split()
  1136. resolve_all = bool(tokens) and tokens[0].lower() == "all"
  1137. reason = (raw_args[len(tokens[0]):].strip() if resolve_all else raw_args)[:280].strip()
  1138. count = resolve_gateway_approval(session_key, "deny", resolve_all=resolve_all, reason=reason or None)
  1139. if not count:
  1140. return t("gateway.deny.no_pending")
  1141. logger.info("User denied %d dangerous command(s) via /deny%s", count,
  1142. " (with reason)" if reason else "")
  1143. key = "gateway.deny.denied" + ("_reason" if reason else "") + ("_plural" if count > 1 else "_singular")
  1144. confirmation_text = t(key, count=count, reason=reason)
  1145. return await self._deliver_approval_confirmation(event, confirmation_text, "deny")
  1146. async def _handle_curator_command(self, event: MessageEvent) -> str:
  1147. """Handle /curator — the ``hermes curator`` handler set (status by default), as main's CLI ran
  1148. it in-process; its printed report is the reply. Runs in the executor with the session's
  1149. context so the profile's skills tree and curator state are the ones read and written."""
  1150. import io
  1151. from contextlib import redirect_stderr, redirect_stdout
  1152. from hermes_cli.curator import cli_main
  1153. tokens = shlex.split(event.get_command_args() or "") or ["status"]
  1154. def _run() -> str:
  1155. out = io.StringIO()
  1156. with redirect_stdout(out), redirect_stderr(out):
  1157. try:
  1158. cli_main(tokens)
  1159. except SystemExit:
  1160. pass # argparse exits on --help/usage errors; its text is the reply
  1161. except Exception as exc: # health: allow BLE001 -- main's CLI handler: the failure line is the reply
  1162. print(t("cli.commands.curator.failed", error=exc))
  1163. return out.getvalue().rstrip()
  1164. return await self._run_in_executor_with_context(_run)
  1165. async def _handle_debug_command(self, event: MessageEvent) -> str:
  1166. """Handle /debug — upload ONLY the summary (system info + log tails), never full logs, to
  1167. protect privacy; ``hermes debug share`` from the CLI does full uploads."""
  1168. from hermes_cli.debug import (_GATEWAY_PRIVACY_NOTICE, _best_effort_sweep_expired_pastes,
  1169. _capture_dump, _is_dpaste_url, _schedule_auto_delete,
  1170. collect_debug_report, upload_to_pastebin)
  1171. from hermes_cli.debug_redaction import redact_debug_support_text
  1172. wants_local = "local" in {w.lower() for w in (event.get_command_args() or "").split()}
  1173. if wants_local and getattr(event.source, "platform", None) != Platform.LOCAL:
  1174. # From a chat the report can't stay on the machine; `/debug local` must never fall
  1175. # through to the public paste. Bare `/debug` is the upload form.
  1176. return t("gateway.debug.local_refused")
  1177. if wants_local:
  1178. # A local session's `/debug local` (main's CLI form) asks for the report on this machine:
  1179. # return the redacted report for the client to show, with no network call at all (not
  1180. # even the expired-paste sweep). Uploading stays on the explicit `/debug` form (T7).
  1181. from hermes_cli.debug import collect_share_bundle
  1182. def _collect_local():
  1183. return collect_share_bundle(log_lines=200)["report"]
  1184. return await self._run_in_executor_with_context(_collect_local)
  1185. def _collect_and_upload(): # blocking I/O (dump capture, log reads, uploads) -> thread
  1186. _best_effort_sweep_expired_pastes()
  1187. report = collect_debug_report(log_lines=200, dump_text=_capture_dump())
  1188. try:
  1189. urls = {t("gateway.debug.report_label"): upload_to_pastebin(report)}
  1190. except Exception as exc:
  1191. return t("gateway.debug.upload_failed", error=redact_debug_support_text(exc))
  1192. _schedule_auto_delete(list(urls.values())) # paste.rs only; dpaste.com has no delete
  1193. label_width = max(len(k) for k in urls)
  1194. # The 6-hour line is only true for paste.rs; the privacy notice above already states
  1195. # the dpaste.com fallback retention, so drop the line rather than contradict it.
  1196. auto_delete = [] if any(map(_is_dpaste_url, urls.values())) else [
  1197. t("gateway.debug.auto_delete")]
  1198. return "\n".join([_GATEWAY_PRIVACY_NOTICE, "", t("gateway.debug.header"), "",
  1199. *(f"`{label:<{label_width}}` {url}" for label, url in urls.items()),
  1200. "", *auto_delete, t("gateway.debug.full_logs_hint"),
  1201. t("gateway.debug.share_hint")])
  1202. # _run_in_executor_with_context, not a bare hop: this collects the profile's logs/config off
  1203. # ``get_hermes_home()`` and uploads them to a public paste. Losing the contextvar override
  1204. # would publish the DEFAULT profile's diagnostics from another profile's chat.
  1205. return await self._run_in_executor_with_context(_collect_and_upload)
  1206. async def _handle_update_command(self, event: MessageEvent) -> str:
  1207. """Handle /update — spawn ``hermes update`` detached (``setsid``) so it survives the gateway
  1208. restart it may trigger; marker files let this or the next gateway process notify the user."""
  1209. import json
  1210. from gateway.run import _hermes_home, _resolve_hermes_bin
  1211. from hermes_cli.config import is_managed, format_managed_message
  1212. # Block non-messaging platforms (API server, webhooks, ACP); plugin platforms with
  1213. # allow_update_command=True are also allowed.
  1214. src = event.source
  1215. if src.platform not in self._UPDATE_ALLOWED_PLATFORMS:
  1216. try:
  1217. from gateway.platform_registry import platform_registry
  1218. entry = platform_registry.get(src.platform.value)
  1219. if not entry or not entry.allow_update_command:
  1220. return t("gateway.update.platform_not_messaging")
  1221. except Exception:
  1222. return t("gateway.update.platform_not_messaging")
  1223. if is_managed():
  1224. return f"✗ {format_managed_message(t('gateway.update.managed_action'))}"
  1225. project_root = Path(__file__).parent.parent.resolve()
  1226. # Not a git-managed install (docker/nix/desktop-app/source): refuse
  1227. # with the steward's own update mechanism instead of git-pulling a
  1228. # tree `hermes update` does not own.
  1229. try:
  1230. from hermes_cli.config import (
  1231. detect_install_method,
  1232. recommended_update_command_for_method,
  1233. )
  1234. method = detect_install_method(project_root)
  1235. if method not in {"git", "unknown"}:
  1236. return t("gateway.update.not_applicable", method=method,
  1237. command=recommended_update_command_for_method(method))
  1238. except Exception:
  1239. pass # config unreadable — fall through to the .git check below
  1240. git_dir = project_root / '.git'
  1241. if not git_dir.exists():
  1242. return t("gateway.update.not_git_repo")
  1243. hermes_cmd = _resolve_hermes_bin()
  1244. if not hermes_cmd:
  1245. return t("gateway.update.hermes_cmd_not_found")
  1246. pending_path = _hermes_home / ".update_pending.json"
  1247. output_path = _hermes_home / ".update_output.txt"
  1248. exit_code_path = _hermes_home / ".update_exit_code"
  1249. pending = {
  1250. "platform": src.platform.value, "chat_id": src.chat_id, "chat_type": src.chat_type,
  1251. "user_id": src.user_id, "session_key": self._session_key_for_source(src),
  1252. "timestamp": datetime.now().isoformat()}
  1253. # ``profile``: the update watcher (possibly the NEXT gateway process) must answer through the
  1254. # requester's own profile bot, not the default profile's adapter for the same platform.
  1255. pending.update({k: v for k, v in (("thread_id", src.thread_id), ("message_id", event.message_id),
  1256. ("profile", getattr(src, "profile", None))) if v})
  1257. _tmp_pending = pending_path.with_suffix(".tmp")
  1258. _tmp_pending.write_text(json.dumps(pending), encoding="utf-8")
  1259. _tmp_pending.replace(pending_path)
  1260. exit_code_path.unlink(missing_ok=True)
  1261. try:
  1262. _spawn_detached_update(hermes_cmd, output_path, exit_code_path)
  1263. except Exception as e:
  1264. pending_path.unlink(missing_ok=True)
  1265. exit_code_path.unlink(missing_ok=True)
  1266. return t("gateway.update.start_failed", error=e)
  1267. self._schedule_update_notification_watch()
  1268. return t("gateway.update.starting")