adapter.py 55 KB

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