adapter.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. """
  2. Chatto Platform Adapter for Hermes Agent.
  3. A plugin-based gateway adapter that connects to a Chatto server
  4. (self-hosted team chat) and relays messages to/from the Hermes agent.
  5. The adapter uses the chattolib library for all Chatto API interactions,
  6. including both outbound messaging and realtime WebSocket connections.
  7. """
  8. from __future__ import annotations
  9. import inspect
  10. import random
  11. from gateway.platforms.helpers import MessageDeduplicator
  12. # Put the vendored dependencies for THIS platform on sys.path before importing
  13. # anything from chattolib. Imported relatively as part of the plugin package and
  14. # absolutely when this module is loaded standalone (e.g. by the tests).
  15. try:
  16. from .vendor_path import setup_vendor_path
  17. except ImportError: # pragma: no cover - depends on how the module is loaded
  18. from vendor_path import setup_vendor_path
  19. setup_vendor_path()
  20. import asyncio
  21. import hashlib
  22. import logging
  23. import mimetypes
  24. import os
  25. from datetime import datetime, timezone
  26. from typing import Any, Dict, List, Literal, Optional, Tuple, cast
  27. from urllib.parse import urlsplit
  28. logger = logging.getLogger(__name__)
  29. from gateway.platforms.base import (
  30. BasePlatformAdapter,
  31. SendResult,
  32. MessageEvent,
  33. MessageType,
  34. ProcessingOutcome,
  35. )
  36. from gateway.config import Platform, PlatformConfig
  37. # Chattolib imports (vendored)
  38. # Using vendored chattolib from vendor/chattolib/
  39. # See vendor_chattolib.sh for how to update the vendored copy
  40. # Absolute imports — vendor/ is on sys.path (see above) and chattolib's own
  41. # modules import each other absolutely. Mixing in relative ".vendor.chattolib"
  42. # imports would load a second, distinct copy of every module, so isinstance()
  43. # checks across the two copies would silently fail.
  44. try:
  45. from chattolib.client import (
  46. ChattoClient,
  47. )
  48. from chattolib.exceptions import (
  49. ChattoAuthError,
  50. ChattoError,
  51. )
  52. from chattolib.realtime import (
  53. ChattoRealtimeError,
  54. ChattoRealtimeCloseError, RealtimeEvent,
  55. stream_events
  56. )
  57. from chattolib.realtime_types import (
  58. MessagePostedPayload
  59. )
  60. from chattolib.types import (
  61. PresenceStatus, RoomKind, User
  62. )
  63. except ImportError as e:
  64. # Fail loudly: continuing here only defers the failure to a confusing
  65. # NameError somewhere deep in the adapter.
  66. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  67. raise
  68. try:
  69. from .platform_config import (
  70. ChattoConfiguration, ChattoConstants,
  71. )
  72. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  73. from platform_config import (
  74. ChattoConfiguration, ChattoConstants,
  75. )
  76. # --------------------------------------------------------------------------- #
  77. # Adapter
  78. # --------------------------------------------------------------------------- #
  79. def hermes_adapter_factory(config: PlatformConfig):
  80. """Factory wrapper that constructs ChattoAdapter from a PlatformConfig."""
  81. return ChattoAdapter(config)
  82. class ChattoAdapter(BasePlatformAdapter):
  83. """Chatto platform adapter — receives messages via WebSocket realtime,
  84. sends via ConnectRPC."""
  85. _SPLIT_THRESHOLD = 9900
  86. splits_long_messages = True
  87. supports_code_blocks: bool = True
  88. supports_status_text: bool = True # client.update_custom_status
  89. def __init__(self, pconfig: PlatformConfig):
  90. """Signature needs to be compatible with BasePlatformAdapter.__init__ """
  91. super().__init__(config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME))
  92. # "extra" has been pre-processed by Hermes-Framework to be a dict of extra config values insode PlatformConfig.
  93. # --- Configuration from our configuration data class with some logic ---
  94. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  95. # ------ State -------
  96. # SDK runtime handle (injected by Hermes); annotate for Pylance
  97. self.sdk: Any = getattr(self, "sdk", None)
  98. # Our own user, filled in by connect(). Events arriving before connect()
  99. # completes must not blow up on an undefined attribute.
  100. self.me: Optional[User] = None
  101. # --- Runtime state ---
  102. self._user_id: str = ""
  103. self._user_display: str = ""
  104. self._room_names: Dict[str, str] = {}
  105. self._room_kinds: Dict[str, RoomKind] = {}
  106. self._our_thread_roots: set = set() # thread root event IDs we created
  107. self._our_message_ids: set = set() # message IDs we sent (for thread root detection)
  108. self._seen: list[str] = [] # Plain RealtimeEvent-id list
  109. self._resume_cursor: Optional[str] = None
  110. self._watch_room_ids: List[str] = []
  111. self._ws_task: Optional[asyncio.Task] = None
  112. self._ws_ready: Optional[asyncio.Event] = None
  113. self._ws_active = False
  114. self._ws_ref = None # reference to open websocket for dynamic resubscribe
  115. # Persistent typing indicator loops per room
  116. self._typing_tasks: Dict[str, asyncio.Task] = {}
  117. # Member directory cache: user_id -> user info dict
  118. self._user_cache: Dict[str, User] = {}
  119. # Chattolib client cache and lock for async access.
  120. self._chatto_client: Optional[ChattoClient] = None
  121. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  122. # Dedup — chattolib may redeliver events across reconnects.
  123. self._dedup = MessageDeduplicator()
  124. def _list_functions(self):
  125. for name, member in inspect.getmembers(self, predicate=callable):
  126. # filtert dunder-Methoden falls gewünscht
  127. if not name.startswith('__'):
  128. logger.info("functions: %s", name)
  129. # ------------------------------------------------------------------ #
  130. # Auth
  131. # ------------------------------------------------------------------ #
  132. async def _get_chatto_client(self: ChattoAdapter) -> Optional[ChattoClient]:
  133. """Get or create a ChattoClient instance."""
  134. if self._chatto_client is not None:
  135. return self._chatto_client
  136. async with self._chatto_client_lock:
  137. if self._chatto_client is not None:
  138. return self._chatto_client
  139. try:
  140. assert(self.chatto_config.login.value) # now we can assume, _login is available.
  141. client = await self._open_client(
  142. base_url=self.chatto_config.base_url.value,
  143. login=self.chatto_config.login.value,
  144. password=self.chatto_config.password.value,
  145. token=self.chatto_config.token.value,
  146. )
  147. self._chatto_client = client
  148. self._token = client.token
  149. logger.info("Chatto: logged in as '%s' via chattolib", self.chatto_config.login.value)
  150. return client
  151. except ChattoAuthError as e:
  152. logger.error("Chatto: authentication failed: %s", e)
  153. return None
  154. except (ChattoError, ValueError) as e:
  155. logger.error("Chatto: failed to create client: %s", e)
  156. return None
  157. async def _require_client(self) -> ChattoClient:
  158. """Return a ChattoClient or raise RuntimeError if unavailable.
  159. Use this helper when the caller expects a client to exist and
  160. wants a single canonical failure path. Methods that prefer a
  161. soft-fail can catch RuntimeError and return gracefully.
  162. """
  163. client = await self._get_chatto_client()
  164. if client is None:
  165. raise RuntimeError("Chatto client unavailable")
  166. return client
  167. async def _ensure_token(self) -> bool:
  168. """Ensure we have a logged-in Chatto client and token."""
  169. if self.chatto_config.token.value and isinstance(self._chatto_client, ChattoClient):
  170. return True
  171. client = await self._get_chatto_client()
  172. return client is not None
  173. async def _relogin(self) -> bool:
  174. """Force re-login (token expired)."""
  175. self._token = None
  176. return await self._ensure_token()
  177. # ------------------------------------------------------------------ #
  178. # Connection
  179. # ------------------------------------------------------------------ #
  180. async def _open_client(
  181. self,
  182. *,
  183. base_url: str,
  184. login: str,
  185. password: str,
  186. token: Optional[str] = None,
  187. ) -> ChattoClient:
  188. """Return a connected ``ChattoClient`` using token or login/password."""
  189. if token:
  190. return ChattoClient(token=token, base_url=base_url)
  191. return await ChattoClient.login(login, password, base_url=base_url)
  192. async def connect(self, *, is_reconnect: bool = False) -> bool:
  193. """Connect to Chatto and start the realtime event stream.
  194. BasePlatformAdapter override
  195. """
  196. logger.info("Chatto: connecting...")
  197. if not await self._ensure_token():
  198. return False
  199. try:
  200. client = await self._require_client()
  201. except RuntimeError:
  202. self._set_fatal_error("connect_failed", "Chatto client not available", retryable=True)
  203. return False
  204. # Get our first own user info
  205. try:
  206. self.me = await client.me()
  207. except Exception as exc:
  208. logger.error("Chatto: failed to get user info: %s", exc)
  209. self._set_fatal_error(
  210. "chatto_auth_failed",
  211. f"Chatto auth failed: {exc}",
  212. retryable=False,
  213. )
  214. try:
  215. assert(self._chatto_client)
  216. await self._chatto_client.close()
  217. finally:
  218. self._chatto_client = None
  219. return False
  220. # Broadcast online presence so the bot appears online in the member list
  221. try:
  222. await client.update_presence(status=PresenceStatus.ONLINE)
  223. except Exception:
  224. logger.debug("Chatto: update_presence(online) failed on connect", exc_info=True)
  225. self._closing = False
  226. # Start background realtime WS event stream loop.
  227. self._ws_ready = asyncio.Event()
  228. self._ws_task = asyncio.create_task(
  229. self._chattolib_event_loop(), name="chatto-event-stream",
  230. )
  231. self._mark_connected()
  232. self._list_functions()
  233. logger.info(
  234. "Chatto: connected and authentiated to %s using login:'%s' (display_name:'%s' id: '%s')",
  235. self.chatto_config.base_url.value,
  236. self.me.login, self.me.display_name, self.me.id
  237. )
  238. return True
  239. async def disconnect(self) -> None:
  240. """Stop WebSocket, liveness probe, typing tasks, and clear state.
  241. BasePlatformAdapter override
  242. """
  243. # Broadcast offline presence before tearing down
  244. try:
  245. client = await self._require_client()
  246. await client.update_presence(status=PresenceStatus.OFFLINE)
  247. except Exception:
  248. logger.debug("Chatto: update_presence(PresenceStatus.OFFLINE) failed on disconnect", exc_info=True)
  249. self._ws_active = False
  250. self._closing = True
  251. # Cancel all typing tasks
  252. for chat_id in list(self._typing_tasks.keys()):
  253. await self.stop_typing(chat_id)
  254. if self._ws_task and not self._ws_task.done():
  255. self._ws_task.cancel()
  256. try:
  257. await self._ws_task
  258. except (asyncio.CancelledError, Exception):
  259. pass
  260. self._ws_task = None
  261. if self._chatto_client:
  262. try:
  263. await self._chatto_client.close()
  264. except Exception:
  265. logger.exception("Chatto: error closing client")
  266. finally:
  267. self._chatto_client = None
  268. self._token = None
  269. logger.info("Chatto: disconnected")
  270. self._mark_disconnected()
  271. async def _seed_room(self, room_id: str) -> None:
  272. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  273. try:
  274. try:
  275. client = await self._require_client()
  276. timeline_page = await client.get_room_events(room_id)
  277. except RuntimeError:
  278. logger.debug("Chatto: _seed_room aborted - no client available for %s", room_id)
  279. return
  280. for ev in timeline_page.events:
  281. if ev.id:
  282. self._mark_seen(ev.id)
  283. logger.debug("Chatto: seeded room %s with %d events", room_id, len(timeline_page.events))
  284. except Exception as e:
  285. logger.debug("Chatto: get room events failed for %s: %s", room_id, e)
  286. # ------------------------------------------------------------------ #
  287. # Realtime Event List
  288. # ------------------------------------------------------------------ #
  289. def _mark_seen(self, event_id: str) -> None:
  290. self._seen.append(event_id)
  291. while len(self._seen) > ChattoConstants.SEEN_CAP:
  292. self._seen.remove(self._seen[0]) # fastest removal of first item in a list.
  293. def _is_seen(self, event_id: str) -> bool:
  294. return event_id in self._seen
  295. # ------------------------------------------------------------------ #
  296. # WebSocket Realtime Transport
  297. # ------------------------------------------------------------------ #
  298. def _check_auth(self, user: User) -> bool:
  299. """We roll our own auth-systen on the against the chatto_config'ured allowed_users etc.
  300. because.. Hermes authz_mixin.py IS NOT SANE.
  301. """
  302. if self.chatto_config.allow_all_users.value:
  303. return True
  304. if user.login in self.chatto_config.allowed_users.value:
  305. return True
  306. if user.id in self.chatto_config.allowed_users.value:
  307. return True
  308. logger.info("Chatto: rejecting message from unauthorized user '%s' (%s)", user.login, user.id)
  309. return False
  310. async def _dispatch_message_posted(self, payload: MessagePostedPayload) -> None:
  311. try:
  312. client = await self._require_client()
  313. except RuntimeError:
  314. logger.warning("Chatto: chattolib event loop aborted - no client available")
  315. return
  316. logger.info("Chatto WS: 'message_posted' event_payload:%s", payload)
  317. message = await payload.fetch_message(client=client)
  318. if message is None or message.deleted_at:
  319. return
  320. message_body = message.body
  321. if not message_body:
  322. return
  323. if message.actor_id in self._user_cache:
  324. # try the user cache.
  325. user = self._user_cache.get(message.actor_id)
  326. else:
  327. # get the user and update cache.
  328. directory_member = await client.get_user(user_id=message.actor_id)
  329. if directory_member is None:
  330. return
  331. user = directory_member.user
  332. if user is None:
  333. return
  334. self._user_cache[user.id] = user
  335. if user is None:
  336. return
  337. if not self._check_auth(user):
  338. return
  339. # For DMs, always respond. For rooms with require_mention, only respond when mentioned.
  340. # Strip the mention from the text for the agent
  341. # Todo: use a function that either reads from cache or gets room kind again.
  342. if self._room_kinds.get(message.room_id) is None:
  343. room_viewer_state = await client.get_room(message.room_id)
  344. if room_viewer_state is None:
  345. return
  346. if room_viewer_state.room is None:
  347. return
  348. self._room_kinds[message.room_id] = room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  349. room_kind = self._room_kinds.get(message.room_id)
  350. logger.info("message_body: %s room_kind: %s", message_body, room_kind)
  351. mentioned = False
  352. if (room_kind == RoomKind.CHANNEL and self.chatto_config.require_mention.value and self.me):
  353. if self.me.login and not mentioned:
  354. mentioned = bool(f"@{self.me.login}" in message_body)
  355. if self.me.display_name and not mentioned:
  356. mentioned = bool(f"@{self.me.display_name}" in message_body)
  357. if mentioned is False:
  358. logger.debug("Discarding message. Bot was not mentionend but require_mention is '%s'.", self.chatto_config.require_mention.value)
  359. return
  360. logger.info("mentioned: %s", mentioned)
  361. # Thread anchoring — if the incoming message is inside a thread, we
  362. # keep that thread by default; otherwise leave thread_id unset so
  363. # replies land at the root.
  364. thread_id = payload.thread_root_event_id or None
  365. if not thread_id and room_kind != RoomKind.DM and self.chatto_config.auto_thread.value:
  366. thread_id = message.id
  367. source = self.build_source(
  368. chat_id=payload.room_id,
  369. chat_name=self._room_names.get(message.room_id),
  370. chat_type="dm" if room_kind == RoomKind.DM else room_kind or RoomKind.UNSPECIFIED, # Only "dm" seems to be a reserved keyword from Base adapter class.,
  371. user_id=message.actor_id,
  372. user_name=user.login, # use login, because display_name is changeable by anyone.
  373. thread_id=thread_id,
  374. message_id=payload.message_event_id,
  375. role_authorized=True,
  376. )
  377. msg_type = MessageType.COMMAND if (message_body.lstrip().startswith("/")) else MessageType.TEXT
  378. my_body = message_body.lstrip() if msg_type == MessageType.COMMAND else message_body
  379. message_event = MessageEvent(
  380. text=my_body,
  381. source=source,
  382. message_id=message.id,
  383. message_type=msg_type,
  384. timestamp=message.created_at or datetime.now(timezone.utc),
  385. raw_message=message,
  386. reply_to_message_id=message.id,
  387. reply_to_text=message_body,
  388. reply_to_author_id=user.id,
  389. reply_to_author_name=user.login,
  390. )
  391. logger.info("Chatto: Dispatching MessageEvent to Hermes: %s", message_event)
  392. await self.handle_message(message_event)
  393. return
  394. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  395. if self._is_seen(event.id):
  396. return
  397. if event.actor_id is None:
  398. return
  399. logger.info("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  400. if (event_payload := event.get("message_posted")) is not None:
  401. # Self-event filter — the actor_id on the envelope is authoritative
  402. # (chattolib does NOT filter this itself; see chatto-bridge notes).
  403. actor_id = event.actor_id
  404. if actor_id and self.me and actor_id == self.me.id:
  405. return
  406. await self._dispatch_message_posted(event_payload)
  407. # confirmed:
  408. elif event.kind in ("mention_notification", "projection_event", "presence_changed", "notification_dismissed",
  409. "room_marked_as_read", "user_typing", "notification_created", "new_direct_message_notification",
  410. 'reaction_removed', 'reaction_added'):
  411. logger.debug("Chatto: '%s' event received. Not yet implemented or not needed.", event.kind)
  412. else:
  413. logger.error("Chatto: unknown event kind: '%s'", event.kind)
  414. async def _chattolib_event_loop(self) -> None:
  415. """Event loop using chattolib's stream_events.
  416. This replaces the manual WebSocket loop with chattolib's high-level
  417. stream_events() which provides pre-decoded RealtimeEvent objects.
  418. """
  419. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  420. while not self._closing:
  421. try:
  422. client = await self._require_client()
  423. await self._refresh_rooms()
  424. logger.info("Chatto: starting chattolib event stream with %d rooms", len(self._watch_room_ids))
  425. async for event in stream_events(client):
  426. if self._closing:
  427. return
  428. await self._handle_realtime_event(event)
  429. # Iterator exited cleanly — treat as a normal close and reconnect
  430. # with the local backoff (no server hint available).
  431. logger.info("Chatto: realtime stream ended, reconnecting")
  432. except asyncio.CancelledError:
  433. return
  434. except ChattoRealtimeCloseError as exc:
  435. if not exc.reconnect:
  436. logger.error(
  437. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  438. exc.code, exc.message,
  439. )
  440. return
  441. wait = max(exc.retry_after_ms / 1000.0, ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF)
  442. logger.warning(
  443. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  444. exc.code, wait,
  445. )
  446. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF # server hint supersedes local backoff
  447. await self._sleep_interruptible(wait)
  448. continue
  449. except ChattoRealtimeError as exc:
  450. if getattr(exc, "fatal", False):
  451. logger.error("Chatto: fatal realtime error (%s): %s", exc.code, exc.message)
  452. return
  453. logger.warning(
  454. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  455. exc.code, exc.message, delay,
  456. )
  457. except Exception as exc:
  458. logger.warning(
  459. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  460. exc, delay,
  461. )
  462. if self._closing:
  463. return
  464. jitter = delay * 0.2 * random.random()
  465. await self._sleep_interruptible(delay + jitter)
  466. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  467. async def _sleep_interruptible(self, seconds: float) -> None:
  468. """Sleep in short slices so disconnect() cancels promptly."""
  469. end = asyncio.get_running_loop().time() + seconds
  470. while not self._closing:
  471. remaining = end - asyncio.get_running_loop().time()
  472. if remaining <= 0:
  473. return
  474. await asyncio.sleep(min(remaining, 0.5))
  475. async def _refresh_rooms(self) -> None:
  476. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms."""
  477. try:
  478. client = await self._require_client()
  479. except RuntimeError:
  480. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  481. return
  482. try:
  483. rooms_list = await client.list_rooms()
  484. new_room_ids: List[str] = []
  485. for room_with_state in rooms_list:
  486. if not room_with_state:
  487. continue
  488. room_obj = room_with_state.room or None
  489. if not room_obj:
  490. continue
  491. self._room_names[room_obj.id] = room_obj.name
  492. self._room_kinds[room_obj.id] = room_obj.kind
  493. if room_with_state.viewer_state.is_member and room_obj.id not in self._watch_room_ids:
  494. new_room_ids.append(room_obj.id)
  495. if not new_room_ids:
  496. return
  497. logger.info("Chatto WS: discovered %d new room(s): %s", len(new_room_ids), new_room_ids)
  498. for rid in new_room_ids:
  499. if self._room_kinds.get(rid) != RoomKind.DM:
  500. await client.join_room(rid) # but list_rooms() would not return any if we were not already joined?!
  501. await self._seed_room(rid)
  502. self._watch_room_ids.append(rid)
  503. watch_room_names: list[str] = []
  504. for rid in self._watch_room_ids:
  505. watch_room_names.append(self._room_names[rid] + " (" + rid + ")")
  506. logger.info("Chatto WS: Watching %d room(s): %s", len(self._watch_room_ids), ", ".join(watch_room_names))
  507. except Exception:
  508. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  509. # ------------------------------------------------------------------ #
  510. # Read state & notification dismissal (best-effort, Chatto-unique)
  511. # ------------------------------------------------------------------ #
  512. # Best-effort: mark all watched rooms as read (room_id may be undefined here)
  513. for _rid in list(self._watch_room_ids):
  514. try:
  515. await client.mark_room_as_read(room_id=_rid)
  516. await client.dismiss_all_notifications()
  517. except Exception:
  518. logger.debug("Chatto: mark_room_as_read failed for %s", _rid, exc_info=True)
  519. # ------------------------------------------------------------------ #
  520. # Sending (ConnectRPC — unchanged from polling version)
  521. # ------------------------------------------------------------------ #
  522. async def send(
  523. self,
  524. chat_id: str,
  525. content: str,
  526. reply_to: Optional[str] = None,
  527. metadata: Optional[Dict[str, Any]] = None,
  528. ) -> SendResult:
  529. """Send a message to a Chatto room.
  530. Long messages are split into chunks via ``truncate_message`` and
  531. each chunk is sent as a separate CreateMessage call. The first
  532. chunk's message ID is returned as ``message_id``.
  533. When ``auto_thread`` is enabled and the incoming message was a
  534. regular room message (not already in a thread), the first chunk is
  535. sent as a room message and its ID becomes the thread root. Subsequent
  536. chunks are sent in that thread. This mirrors Discord's auto_thread
  537. behavior.
  538. BasePlatformAdapter override
  539. """
  540. if not content:
  541. return SendResult(success=False, error="Empty message")
  542. formatted = self.format_message(content) if hasattr(self, "format_message") else content
  543. chunks = self.truncate_message(formatted, ChattoConstants.MAX_MESSAGE_LENGTH)
  544. # Thread support — resolve thread_id once
  545. # DM rooms don't support threads, so skip threading for DMs
  546. thread_id = (metadata or {}).get("thread_id")
  547. # Only use reply_to as thread_id if auto_thread is enabled.
  548. # When auto_thread=false, responses go directly in the room
  549. # without threading under the incoming message.
  550. if reply_to and self.chatto_config.auto_thread.value:
  551. # reply_to might be the incoming message ID. If we already have
  552. # thread_id from metadata, keep it (it's the thread root).
  553. # Only use reply_to as thread_id if we don't already have one.
  554. if not thread_id:
  555. thread_id = reply_to
  556. # Check if this is a DM room — DMs don't support threads
  557. room_kind = self._room_kinds.get(chat_id)
  558. is_dm = room_kind == RoomKind.DM
  559. if is_dm:
  560. thread_id = None
  561. # Auto-thread: by default, Chatto creates a thread for replies to room
  562. # messages (not DMs, not already in a thread). This keeps conversations
  563. # organized in the room. Can be disabled via extra.auto_thread=false.
  564. use_auto_thread = self.chatto_config.auto_thread.value and not thread_id and not is_dm
  565. message_ids: List[str] = []
  566. last_resp: Optional[Any] = None
  567. last_error: Optional[str] = None
  568. retryable = False
  569. try:
  570. client = await self._require_client()
  571. except RuntimeError:
  572. return SendResult(success=False, error="Chatto client not available", retryable=True)
  573. for i, chunk in enumerate(chunks):
  574. try:
  575. msg_obj = await client.post_message(
  576. room_id=chat_id,
  577. body=chunk,
  578. thread_root_event_id=str(thread_id) if thread_id else "",
  579. )
  580. except ChattoError as e:
  581. last_error = str(e)
  582. retryable = True
  583. break
  584. except Exception as e:
  585. last_error = str(e)
  586. retryable = True
  587. break
  588. last_resp = msg_obj
  589. self._mark_seen(msg_obj.id)
  590. message_ids.append(msg_obj.id)
  591. self._our_message_ids.add(msg_obj.id)
  592. # If we sent a message WITHOUT a thread_id, this message could
  593. # become a thread root if someone replies to it
  594. if not thread_id:
  595. self._our_thread_roots.add(msg_obj.id)
  596. # Auto-thread: first chunk becomes the thread root,
  597. # subsequent chunks go in the thread
  598. if use_auto_thread and i == 0 and not thread_id:
  599. thread_id = msg_obj.id
  600. # Nothing got through at all — report the failure instead of a phantom success.
  601. if not message_ids:
  602. return SendResult(
  603. success=False,
  604. error=last_error or "Chatto: message could not be sent",
  605. retryable=retryable,
  606. )
  607. first_id = message_ids[0]
  608. # ------------------------------------------------------------------ #
  609. # Thread following (best-effort, Chatto-unique)
  610. # ------------------------------------------------------------------ #
  611. if thread_id:
  612. try:
  613. await client.follow_thread(chat_id, thread_id)
  614. except Exception:
  615. logger.debug("Chatto: follow_thread failed for %s/%s", chat_id, thread_id, exc_info=True)
  616. # A later chunk failed after earlier ones went out: partial delivery.
  617. if last_error:
  618. logger.warning(
  619. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  620. len(message_ids), len(chunks), chat_id, last_error,
  621. )
  622. return SendResult(success=True, message_id=first_id, raw_response=last_resp)
  623. # Overridden from BaseAdapter:
  624. async def send_typing(self, chat_id: str, metadata=None) -> None:
  625. """Start a persistent typing indicator for a room.
  626. Sends a typing ping every 10 seconds (Chatto's indicator likely
  627. lasts ~8-10s). The background loop runs until ``stop_typing()``
  628. is called or the task is cancelled.
  629. BasePlatformAdapter override
  630. """
  631. if chat_id in self._typing_tasks:
  632. return # already running
  633. async def _typing_loop() -> None:
  634. try:
  635. while True:
  636. try:
  637. try:
  638. client = await self._require_client()
  639. except RuntimeError:
  640. return
  641. await client.update_typing_indicator(room_id=str(chat_id))
  642. except asyncio.CancelledError:
  643. return
  644. except Exception:
  645. pass
  646. await asyncio.sleep(10)
  647. except asyncio.CancelledError:
  648. pass
  649. finally:
  650. self._typing_tasks.pop(chat_id, None)
  651. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  652. async def stop_typing(self, chat_id: str) -> None:
  653. """Stop the persistent typing indicator for a room.
  654. BasePlatformAdapter override
  655. """
  656. task = self._typing_tasks.pop(chat_id, None)
  657. if task:
  658. task.cancel()
  659. try:
  660. await task
  661. except (asyncio.CancelledError, Exception):
  662. pass
  663. async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
  664. """Get information about a chat/room.
  665. BasePlatformAdapter override
  666. """
  667. name = self._room_names.get(chat_id, chat_id)
  668. kind = self._room_kinds.get(chat_id)
  669. chat_type = "dm" if kind == RoomKind.DM else "group"
  670. return {
  671. "name": name,
  672. "type": chat_type,
  673. }
  674. # ------------------------------------------------------------------ #
  675. # Reactions
  676. # ------------------------------------------------------------------ #
  677. @staticmethod
  678. def _emoji_to_shortcode(emoji: str) -> str:
  679. """Convert a unicode emoji to a Chatto shortcode name.
  680. If the emoji is already a shortcode (no unicode mapping found),
  681. return it as-is.
  682. """
  683. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  684. if shortcode:
  685. return shortcode
  686. # Already a shortcode like "thumbsup" — return as-is
  687. return emoji
  688. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  689. """Add a reaction to a message via MessageService/AddReaction."""
  690. shortcode = self._emoji_to_shortcode(emoji)
  691. try:
  692. try:
  693. client = await self._require_client()
  694. except RuntimeError:
  695. logger.warning("Chatto: AddReaction — client unavailable")
  696. return False
  697. result = await client.add_reaction(
  698. room_id=room_id,
  699. message_event_id=message_id,
  700. emoji=shortcode,
  701. )
  702. return result
  703. except ChattoError as e:
  704. logger.warning("Chatto: AddReaction failed: %s", e)
  705. return False
  706. except Exception as e:
  707. logger.warning("Chatto: AddReaction error: %s", e)
  708. return False
  709. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  710. """Remove a reaction from a message via MessageService/RemoveReaction."""
  711. shortcode = self._emoji_to_shortcode(emoji)
  712. try:
  713. try:
  714. client = await self._require_client()
  715. except RuntimeError:
  716. logger.warning("Chatto: RemoveReaction — client unavailable")
  717. return False
  718. result = await client.remove_reaction(
  719. room_id=str(chat_id),
  720. message_event_id=str(message_id),
  721. emoji=shortcode,
  722. )
  723. return result
  724. except ChattoError as e:
  725. logger.warning("Chatto: RemoveReaction failed: %s", e)
  726. return False
  727. except Exception as e:
  728. logger.warning("Chatto: RemoveReaction error: %s", e)
  729. return False
  730. # ------------------------------------------------------------------ #
  731. # DM initiation (Chatto-unique)
  732. # ------------------------------------------------------------------ #
  733. async def start_dm(self, user_id: str) -> Optional[str]:
  734. """Start a direct message with a user via RoomService/StartDM.
  735. Returns the room ID on success, or None on failure.
  736. """
  737. if not user_id:
  738. return None
  739. try:
  740. try:
  741. client = await self._require_client()
  742. except RuntimeError:
  743. return None
  744. room = await client.start_dm(participant_ids=[str(user_id)])
  745. self._room_names[room.id] = room.name
  746. self._room_kinds[room.id] = room.kind
  747. return room.id
  748. except ChattoError as e:
  749. logger.debug("Chatto: StartDM failed: %s", e)
  750. return None
  751. except Exception as e:
  752. logger.debug("Chatto: StartDM error: %s", e)
  753. return None
  754. # ------------------------------------------------------------------ #
  755. # Room creation (Chatto-unique)
  756. # ------------------------------------------------------------------ #
  757. async def create_room(
  758. self,
  759. name: str,
  760. description: str = "",
  761. group_id: str = "",
  762. universal: bool = True,
  763. ) -> Optional[str]:
  764. """Create an ad-hoc room via RoomService/CreateRoom.
  765. Returns the room ID on success, or None on failure.
  766. """
  767. try:
  768. try:
  769. client = await self._require_client()
  770. except RuntimeError:
  771. return None
  772. room = await client.create_room(
  773. name=name,
  774. group_id=group_id or "",
  775. description=description,
  776. universal=universal,
  777. )
  778. rid = str(room.id) if room else ""
  779. if rid:
  780. self._room_names[rid] = room.name
  781. self._room_kinds[rid] = room.kind
  782. return rid
  783. logger.debug("Chatto: CreateRoom returned no room id")
  784. return None
  785. except ChattoError as e:
  786. logger.debug("Chatto: CreateRoom failed: %s", e)
  787. return None
  788. except Exception as e:
  789. logger.debug("Chatto: CreateRoom error: %s", e)
  790. return None
  791. # ------------------------------------------------------------------ #
  792. # Processing lifecycle hooks (reactions-based, like Discord)
  793. # ------------------------------------------------------------------ #
  794. def _event_room_and_message_id(self, event: MessageEvent) -> Tuple[str, str]:
  795. """Extract room_id and message_id from a MessageEvent."""
  796. message_id = event.message_id or ""
  797. chat_id = event.source.chat_id
  798. return chat_id, message_id
  799. async def on_processing_start(self, event: MessageEvent) -> None:
  800. """Add an 👀 (eyes) reaction to the incoming message.
  801. BasePlatformAdapter override
  802. """
  803. logger.info("self.chatto_config.reactions.value: %s", self.chatto_config.reactions.value)
  804. if not self.chatto_config.reactions.value:
  805. return
  806. chat_id, message_id = self._event_room_and_message_id(event)
  807. if not chat_id or not message_id:
  808. logger.warning("Chatto: on_processing_start — empty chat_id or message_id, skipping reaction")
  809. return
  810. await self.add_reaction(chat_id, message_id, "👀")
  811. async def on_processing_complete(
  812. self, event: MessageEvent, outcome: ProcessingOutcome
  813. ) -> None:
  814. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  815. BasePlatformAdapter override
  816. """
  817. if not self.chatto_config.reactions.value:
  818. return
  819. chat_id, message_id = self._event_room_and_message_id(event)
  820. if not chat_id or not message_id:
  821. return
  822. # Remove the processing eyes reaction
  823. await self.remove_reaction(chat_id, message_id, "👀")
  824. # Add the outcome reaction
  825. if outcome == ProcessingOutcome.SUCCESS:
  826. await self.add_reaction(chat_id, message_id, "✅")
  827. elif outcome == ProcessingOutcome.FAILURE:
  828. await self.add_reaction(chat_id, message_id, "❌")
  829. # ------------------------------------------------------------------ #
  830. # Asset upload (chunked)
  831. # ------------------------------------------------------------------ #
  832. async def _upload_asset(self, room_id: str, file_path: str) -> Optional[str]:
  833. """Upload a file via the chunked AssetUploadService.
  834. Returns the asset ID on success, or None on failure.
  835. """
  836. try:
  837. with open(file_path, "rb") as f:
  838. file_data = f.read()
  839. except Exception as e:
  840. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  841. return None
  842. if not file_data:
  843. logger.error("Chatto: file %s is empty", file_path)
  844. return None
  845. file_size = len(file_data)
  846. file_name = os.path.basename(file_path)
  847. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  848. sha256_hash = hashlib.sha256(file_data).hexdigest()
  849. try:
  850. try:
  851. client = await self._require_client()
  852. except RuntimeError:
  853. logger.error("Chatto: upload aborted - no client available")
  854. return None
  855. # Step 1: Create upload session
  856. upload = await client.create_upload(
  857. room_id=room_id,
  858. filename=file_name,
  859. size=file_size,
  860. sha256=sha256_hash,
  861. content_type=mime_type,
  862. )
  863. upload_id = str(getattr(cast(Any, upload), "id", ""))
  864. if not upload_id:
  865. logger.error("Chatto: CreateUpload returned no upload ID")
  866. return None
  867. # Step 2: Upload chunks
  868. offset = 0
  869. while offset < file_size:
  870. chunk = file_data[offset:offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  871. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  872. await client.upload_chunk(
  873. upload_id=upload_id,
  874. offset=offset,
  875. content=chunk,
  876. chunk_sha256=chunk_sha256,
  877. )
  878. offset += len(chunk)
  879. # Step 3: Complete upload
  880. upload, asset = await client.complete_upload(upload_id=upload_id)
  881. if not asset:
  882. logger.error("Chatto: CompleteUpload returned no asset")
  883. return None
  884. asset_id = str(getattr(cast(Any, asset), "id", ""))
  885. logger.info("Chatto: uploaded %s as asset %s (%d bytes)", file_name, asset_id, file_size)
  886. return asset_id
  887. except ChattoError as e:
  888. logger.error("Chatto: upload failed: %s", e)
  889. return None
  890. except Exception as e:
  891. logger.error("Chatto: upload error: %s", e)
  892. return None
  893. async def send_image_file(
  894. self,
  895. chat_id: str,
  896. file_path: str,
  897. caption: Optional[str] = None,
  898. reply_to: Optional[str] = None,
  899. metadata: Optional[Dict[str, Any]] = None,
  900. ) -> SendResult:
  901. """Send a local image file via the chunked upload API. Do not change signature.
  902. BasePlatformAdapter override
  903. """
  904. # Validate the path is safe
  905. safe_path = self.validate_media_delivery_path(file_path)
  906. if not safe_path:
  907. logger.warning("Chatto: send_image_file — unsafe path %s", file_path)
  908. text = "⚠️ Couldn't deliver the image attachment."
  909. if caption:
  910. text = f"{caption}\n{text}"
  911. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  912. asset_id = await self._upload_asset(str(chat_id), safe_path)
  913. if not asset_id:
  914. # Fallback to a notice
  915. text = "⚠️ Couldn't deliver the image attachment."
  916. if caption:
  917. text = f"{caption}\n{text}"
  918. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  919. thread_id = (metadata or {}).get("thread_id")
  920. if reply_to:
  921. thread_id = reply_to
  922. try:
  923. try:
  924. client = await self._require_client()
  925. except RuntimeError:
  926. return SendResult(success=False, error="Chatto client not available", retryable=True)
  927. msg = await client.post_message(
  928. room_id=str(chat_id),
  929. body=caption or "",
  930. attachment_asset_ids=[asset_id],
  931. thread_root_event_id=str(thread_id) if thread_id else "",
  932. )
  933. self._mark_seen(msg.id)
  934. return SendResult(success=True, message_id=msg.id, raw_response=msg)
  935. except ChattoError as e:
  936. return SendResult(success=False, error=str(e), retryable=True)
  937. except Exception as e:
  938. return SendResult(success=False, error=str(e), retryable=False)
  939. async def send_image(
  940. self,
  941. chat_id: str,
  942. image_url: str,
  943. caption: Optional[str] = None,
  944. reply_to: Optional[str] = None,
  945. metadata: Optional[Dict[str, Any]] = None,
  946. ) -> SendResult:
  947. """Send an image to a Chatto room.
  948. Tries to download the image from the URL and upload it as a native
  949. attachment. Falls back to sending the URL as a link (Chatto renders
  950. link previews) if the download fails.
  951. BasePlatformAdapter override
  952. """
  953. # Try downloading and uploading as attachment
  954. try:
  955. import tempfile
  956. import urllib.request as _urllib_request
  957. # Download to a temp file
  958. parsed = urlsplit(image_url)
  959. url_path = parsed.path
  960. ext = os.path.splitext(url_path)[1] or ".png"
  961. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  962. try:
  963. os.close(tmp_fd)
  964. req = _urllib_request.Request(image_url, headers={"User-Agent": "Hermes/1.0"})
  965. try:
  966. import ssl
  967. ctx = ssl.create_default_context()
  968. except Exception:
  969. ctx = None
  970. with _urllib_request.urlopen(req, timeout=ChattoConstants.HTTP_TIMEOUT, context=ctx) as resp:
  971. with open(tmp_path, "wb") as f:
  972. f.write(resp.read())
  973. # Upload as attachment
  974. result = await self.send_image_file(
  975. chat_id, tmp_path, caption=caption,
  976. reply_to=reply_to, metadata=metadata,
  977. )
  978. if result.success:
  979. return result
  980. finally:
  981. try:
  982. os.unlink(tmp_path)
  983. except OSError:
  984. pass
  985. except Exception as e:
  986. logger.debug("Chatto: send_image download/upload failed, falling back to link: %s", e)
  987. # Fallback: send as link (Chatto renders link previews)
  988. text = image_url
  989. if caption:
  990. text = f"{caption}\n{image_url}"
  991. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  992. # ---------------------------------------------------------------------------
  993. # Cron / out-of-process delivery
  994. # ---------------------------------------------------------------------------
  995. async def hermes_standalone_sender_fn(
  996. pconfig,
  997. chat_id,
  998. message,
  999. *,
  1000. thread_id=None,
  1001. media_files=None,
  1002. force_document=False,
  1003. ) -> SendResult:
  1004. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  1005. Used by cron / scheduled routines that run out-of-process. Creates a
  1006. short-lived chattolib client, posts, and closes.
  1007. """
  1008. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  1009. # Create a temporary client for standalone sending — we need a base URL plus
  1010. # either a token or a full login/password pair.
  1011. has_credentials = bool(
  1012. chatto_config.token.value
  1013. or (chatto_config.login.value and chatto_config.password.value)
  1014. )
  1015. if not chatto_config.base_url.value or not has_credentials:
  1016. return SendResult(success=False, error="Chatto: base URL or credentials missing")
  1017. client: ChattoClient
  1018. try:
  1019. if chatto_config.token.value:
  1020. client = ChattoClient(base_url=chatto_config.base_url.value, token=chatto_config.token.value)
  1021. else:
  1022. client = await ChattoClient.login(
  1023. base_url=chatto_config.base_url.value,
  1024. login=chatto_config.login.value,
  1025. password=chatto_config.password.value,
  1026. )
  1027. except Exception as exc:
  1028. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  1029. try:
  1030. kwargs: Dict[str, Any] = {}
  1031. if chatto_config.auto_thread.value and thread_id:
  1032. kwargs["in_reply_to"] = thread_id
  1033. if media_files and media_files.get("attachment_asset_ids"):
  1034. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  1035. try:
  1036. posted = await client.post_message(chat_id, message, **kwargs)
  1037. except Exception as exc:
  1038. return SendResult(success=False, error=str(exc))
  1039. return SendResult(success=True, message_id=getattr(posted, "id", "") or None)
  1040. finally:
  1041. try:
  1042. await client.close()
  1043. except Exception as exc:
  1044. logger.error(
  1045. "Chatto standalone: error closing short-lived client (perhaps already closed): %s", exc,
  1046. )
  1047. def hermes_validate_config(config: PlatformConfig) -> bool:
  1048. """"
  1049. Function name should be the same as register argument name with "hermes_" prefix, so we
  1050. know that it is needed for plugin register(). Do not change signature.
  1051. - config
  1052. Check whether Chatto Plugin is configured. Compare to hermes_is_connected()."""
  1053. chatto_config = ChattoConfiguration(pconfig=config)
  1054. if len(chatto_config.allowed_users.value) > 0 and chatto_config.allow_all_users.value:
  1055. logger.info("Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both.")
  1056. return False
  1057. if chatto_config.base_url.value:
  1058. if (chatto_config.token.value is not None) or (chatto_config.login.value and chatto_config.password.value):
  1059. return True
  1060. else:
  1061. logger.error("Chatto: Minimally, either token or login/password must be set.")
  1062. else:
  1063. logger.error("Chatto: base_url must be set.")
  1064. return False
  1065. def hermes_check_fn() -> bool:
  1066. """Check if Chatto is configured and dependencies are available.
  1067. Add real logic?! Or just .. there are no dependencies.. always return true. Really. Docs suck."""
  1068. try:
  1069. import chattolib.client # noqa: F401 — vendored dependency probe
  1070. return True
  1071. except ImportError:
  1072. return False
  1073. # ---------------------------------------------------------------------------
  1074. # is_connected probe
  1075. # ---------------------------------------------------------------------------
  1076. def hermes_is_connected(config: PlatformConfig) -> bool:
  1077. """Check whether Chatto Plugin is connected. But where to? To the Hermes Agent? To Chatto Server?
  1078. The Hermes Agent plugin docs suck and it seems there are many functions to do the same."""
  1079. return bool(hermes_validate_config(config) and config.enabled)
  1080. def hermes_setup_fn() -> None:
  1081. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  1082. Function name should be the same as register argument name with "hermes_" prefix, so we
  1083. know that it is needed for plugin register().
  1084. """
  1085. from hermes_cli.setup import (
  1086. prompt,
  1087. prompt_yes_no,
  1088. save_env_value,
  1089. get_env_value,
  1090. print_header,
  1091. print_info,
  1092. print_warning,
  1093. print_success,
  1094. )
  1095. url = prompt(
  1096. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:")
  1097. if url:
  1098. save_env_value(ChattoConfiguration.base_url.env_name, url)
  1099. login = prompt("Chatto login (username):")
  1100. if login:
  1101. save_env_value(ChattoConfiguration.login.env_name, login)
  1102. password = prompt("Chatto password:", password=True)
  1103. if password:
  1104. save_env_value(ChattoConfiguration.password.env_name, password)
  1105. channels = prompt("Room IDs to watch (comma-separated, or empty for all):")
  1106. if channels:
  1107. save_env_value(ChattoConfiguration.channels_list.env_name, channels)
  1108. home = prompt("Home room ID for notifications (or empty):")
  1109. if home:
  1110. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  1111. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  1112. if allow_all:
  1113. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  1114. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  1115. def hermes_env_enablement_fn() -> Optional[dict]:
  1116. """Seed PlatformConfig.extra from env vars.
  1117. Returns a dict compatible with the PlatformConfig merge hook (or None
  1118. when no env-provided values are present).
  1119. Called by the platform registry during load_gateway_config().
  1120. Return None when the platform isn't minimally configured — the
  1121. caller then skips auto-enabling. Return a dict to seed extras.
  1122. The special 'home_channel' key is extracted and becomes a proper
  1123. HomeChannel dataclass on the PlatformConfig; every other key is
  1124. merged into PlatformConfig.extra.
  1125. Function name should be the same as register argument name with "hermes_" prefix, so we
  1126. know that it is needed for plugin register().
  1127. """
  1128. # Seed keys must be the config.yaml "extra" keys (config_key), NOT the env
  1129. # var names — ChattoConfiguration reads extra[config_key].
  1130. seed: Dict[str, Any] = {
  1131. ChattoConfiguration.base_url.config_key: (
  1132. os.getenv(ChattoConfiguration.base_url.env_name) or ChattoClient.DEFAULT_BASE_URL
  1133. ).strip(),
  1134. }
  1135. for field in ChattoConfiguration.fields():
  1136. if field.field_name == ChattoConfiguration.base_url.field_name:
  1137. continue
  1138. env_value = os.getenv(field.env_name)
  1139. if env_value:
  1140. seed[field.config_key] = env_value.strip()
  1141. logger.debug("seed: %s", {k: v for k, v in seed.items() if k not in ("token", "password")})
  1142. return seed
  1143. # ---------------------------------------------------------------------------
  1144. # Plugin registration entry point
  1145. # ---------------------------------------------------------------------------
  1146. def register(ctx) -> None:
  1147. """Plugin entry point — called by the Hermes plugin system."""
  1148. logger.info("Registering Chatto platform plugin on Hermes Agent")
  1149. logger.info("ChattoConfiguration.allowed_users.env_name: %s", ChattoConfiguration.allowed_users.env_name)
  1150. ctx.register_platform(
  1151. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  1152. label=ChattoConstants.PLATFORM_LABEL,
  1153. adapter_factory=hermes_adapter_factory,
  1154. check_fn=hermes_check_fn,
  1155. validate_config=hermes_validate_config,
  1156. is_connected=hermes_is_connected,
  1157. install_hint=ChattoConstants.INSTALL_HINT,
  1158. env_enablement_fn=hermes_env_enablement_fn,
  1159. setup_fn=hermes_setup_fn,
  1160. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  1161. standalone_sender_fn=hermes_standalone_sender_fn,
  1162. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  1163. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  1164. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  1165. emoji="💬",
  1166. allow_update_command=True,
  1167. pii_safe=False,
  1168. platform_hint=(
  1169. "You are chatting in Chatto (a self-hosted or cloud-hosted team or community chat server). "
  1170. "Markdown is supported. Users _may_ address you by @-mentioning your name. If configured, " \
  1171. "you also react without a @-mention. Direct messages reach you without a mention."
  1172. "Keep responses conversational."
  1173. ),
  1174. )