adapter.py 56 KB

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