adapter.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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 away presence before tearing down
  240. try:
  241. client = await self._require_client()
  242. await client.update_presence(status=PresenceStatus.ONLINE)
  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. # Ensure ws_ready is available for synchronization with starter
  416. backoff = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  417. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  418. while not self._closing:
  419. try:
  420. client = await self._require_client()
  421. await self._refresh_rooms()
  422. logger.info("Chatto: starting chattolib event stream with %d rooms", len(self._watch_room_ids))
  423. async for event in stream_events(client):
  424. if self._closing:
  425. return
  426. await self._handle_realtime_event(event)
  427. # Iterator exited cleanly — treat as a normal close and reconnect
  428. # with the local backoff (no server hint available).
  429. logger.info("Chatto: realtime stream ended, reconnecting")
  430. except asyncio.CancelledError:
  431. return
  432. except ChattoRealtimeCloseError as exc:
  433. if not exc.reconnect:
  434. logger.error(
  435. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  436. exc.code, exc.message,
  437. )
  438. return
  439. wait = max(exc.retry_after_ms / 1000.0, ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF)
  440. logger.warning(
  441. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  442. exc.code, wait,
  443. )
  444. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF # server hint supersedes local backoff
  445. await self._sleep_interruptible(wait)
  446. continue
  447. except ChattoRealtimeError as exc:
  448. if getattr(exc, "fatal", False):
  449. logger.error("Chatto: fatal realtime error (%s): %s", exc.code, exc.message)
  450. return
  451. logger.warning(
  452. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  453. exc.code, exc.message, delay,
  454. )
  455. except Exception as exc:
  456. logger.warning(
  457. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  458. exc, delay,
  459. )
  460. if self._closing:
  461. return
  462. jitter = delay * 0.2 * random.random()
  463. await self._sleep_interruptible(delay + jitter)
  464. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  465. await asyncio.sleep(backoff)
  466. async def _sleep_interruptible(self, seconds: float) -> None:
  467. """Sleep in short slices so disconnect() cancels promptly."""
  468. end = asyncio.get_running_loop().time() + seconds
  469. while not self._closing:
  470. remaining = end - asyncio.get_running_loop().time()
  471. if remaining <= 0:
  472. return
  473. await asyncio.sleep(min(remaining, 0.5))
  474. async def _refresh_rooms(self) -> None:
  475. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms."""
  476. try:
  477. client = await self._require_client()
  478. except RuntimeError:
  479. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  480. return
  481. try:
  482. rooms_list = await client.list_rooms()
  483. new_room_ids: List[str] = []
  484. for room_with_state in rooms_list:
  485. if not room_with_state:
  486. continue
  487. room_obj = room_with_state.room or None
  488. if not room_obj:
  489. continue
  490. self._room_names[room_obj.id] = room_obj.name
  491. self._room_kinds[room_obj.id] = room_obj.kind
  492. if room_with_state.viewer_state.is_member and room_obj.id not in self._watch_room_ids:
  493. new_room_ids.append(room_obj.id)
  494. if not new_room_ids:
  495. return
  496. logger.info("Chatto WS: discovered %d new room(s): %s", len(new_room_ids), new_room_ids)
  497. for rid in new_room_ids:
  498. if self._room_kinds.get(rid) != RoomKind.DM:
  499. await client.join_room(rid) # but list_rooms() would not return any if we were not already joined?!
  500. await self._seed_room(rid)
  501. self._watch_room_ids.append(rid)
  502. watch_room_names: list[str] = []
  503. for rid in self._watch_room_ids:
  504. watch_room_names.append(self._room_names[rid] + " (" + rid + ")")
  505. logger.info("Chatto WS: Watching %d room(s): %s", len(self._watch_room_ids), ", ".join(watch_room_names))
  506. except Exception:
  507. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  508. # ------------------------------------------------------------------ #
  509. # Read state & notification dismissal (best-effort, Chatto-unique)
  510. # ------------------------------------------------------------------ #
  511. # Best-effort: mark all watched rooms as read (room_id may be undefined here)
  512. for _rid in list(self._watch_room_ids):
  513. try:
  514. await client.mark_room_as_read(room_id=_rid)
  515. await client.dismiss_all_notifications()
  516. except Exception:
  517. logger.debug("Chatto: mark_room_as_read failed for %s", _rid, exc_info=True)
  518. # ------------------------------------------------------------------ #
  519. # Sending (ConnectRPC — unchanged from polling version)
  520. # ------------------------------------------------------------------ #
  521. async def send(
  522. self,
  523. chat_id: str,
  524. content: str,
  525. reply_to: Optional[str] = None,
  526. metadata: Optional[Dict[str, Any]] = None,
  527. ) -> SendResult:
  528. """Send a message to a Chatto room.
  529. Long messages are split into chunks via ``truncate_message`` and
  530. each chunk is sent as a separate CreateMessage call. The first
  531. chunk's message ID is returned as ``message_id``.
  532. When ``auto_thread`` is enabled and the incoming message was a
  533. regular room message (not already in a thread), the first chunk is
  534. sent as a room message and its ID becomes the thread root. Subsequent
  535. chunks are sent in that thread. This mirrors Discord's auto_thread
  536. behavior.
  537. BasePlatformAdapter override
  538. """
  539. if not content:
  540. return SendResult(success=False, error="Empty message")
  541. formatted = self.format_message(content) if hasattr(self, "format_message") else content
  542. chunks = self.truncate_message(formatted, ChattoConstants.MAX_MESSAGE_LENGTH)
  543. # Thread support — resolve thread_id once
  544. # DM rooms don't support threads, so skip threading for DMs
  545. thread_id = (metadata or {}).get("thread_id")
  546. # Only use reply_to as thread_id if auto_thread is enabled.
  547. # When auto_thread=false, responses go directly in the room
  548. # without threading under the incoming message.
  549. if reply_to and self.chatto_config.auto_thread.value:
  550. # reply_to might be the incoming message ID. If we already have
  551. # thread_id from metadata, keep it (it's the thread root).
  552. # Only use reply_to as thread_id if we don't already have one.
  553. if not thread_id:
  554. thread_id = reply_to
  555. # Check if this is a DM room — DMs don't support threads
  556. room_kind = self._room_kinds.get(chat_id)
  557. is_dm = room_kind == RoomKind.DM
  558. if is_dm:
  559. thread_id = None
  560. # Auto-thread: by default, Chatto creates a thread for replies to room
  561. # messages (not DMs, not already in a thread). This keeps conversations
  562. # organized in the room. Can be disabled via extra.auto_thread=false.
  563. use_auto_thread = self.chatto_config.auto_thread.value and not thread_id and not is_dm
  564. message_ids: List[str] = []
  565. last_resp: Optional[dict] = None
  566. last_error: Optional[str] = None
  567. retryable = False
  568. try:
  569. client = await self._require_client()
  570. except RuntimeError:
  571. return SendResult(success=False, error="Chatto client not available", retryable=True)
  572. for i, chunk in enumerate(chunks):
  573. try:
  574. msg_obj = await client.post_message(
  575. room_id=chat_id,
  576. body=chunk,
  577. thread_root_event_id=str(thread_id) if thread_id else "",
  578. )
  579. except ChattoError as e:
  580. last_error = str(e)
  581. retryable = True
  582. break
  583. except Exception as e:
  584. last_error = str(e)
  585. retryable = True
  586. break
  587. if last_error and not message_ids:
  588. return SendResult(success=False, error=last_error, retryable=retryable)
  589. self._mark_seen(msg_obj.id)
  590. message_ids.append(msg_obj.id)
  591. self._our_message_ids.add(msg_obj.id)
  592. # If we sent a message WITHOUT a thread_id, this message could
  593. # become a thread root if someone replies to it
  594. if not thread_id:
  595. self._our_thread_roots.add(msg_obj.id)
  596. # Auto-thread: first chunk becomes the thread root,
  597. # subsequent chunks go in the thread
  598. if use_auto_thread and i == 0 and not thread_id:
  599. thread_id = msg_obj.id
  600. first_id = message_ids[0] if message_ids else ""
  601. # ------------------------------------------------------------------ #
  602. # Thread following (best-effort, Chatto-unique)
  603. # ------------------------------------------------------------------ #
  604. if thread_id and message_ids:
  605. await client.follow_thread(chat_id, thread_id)
  606. return SendResult(success=True, message_id=first_id, raw_response=last_resp)
  607. # Overridden from BaseAdapter:
  608. async def send_typing(self, chat_id: str, metadata=None) -> None:
  609. """Start a persistent typing indicator for a room.
  610. Sends a typing ping every 10 seconds (Chatto's indicator likely
  611. lasts ~8-10s). The background loop runs until ``stop_typing()``
  612. is called or the task is cancelled.
  613. BasePlatformAdapter override
  614. """
  615. if chat_id in self._typing_tasks:
  616. return # already running
  617. async def _typing_loop() -> None:
  618. try:
  619. while True:
  620. try:
  621. try:
  622. client = await self._require_client()
  623. except RuntimeError:
  624. return
  625. await client.update_typing_indicator(room_id=str(chat_id))
  626. except asyncio.CancelledError:
  627. return
  628. except Exception:
  629. pass
  630. await asyncio.sleep(10)
  631. except asyncio.CancelledError:
  632. pass
  633. finally:
  634. self._typing_tasks.pop(chat_id, None)
  635. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  636. async def stop_typing(self, chat_id: str) -> None:
  637. """Stop the persistent typing indicator for a room.
  638. BasePlatformAdapter override
  639. """
  640. task = self._typing_tasks.pop(chat_id, None)
  641. if task:
  642. task.cancel()
  643. try:
  644. await task
  645. except (asyncio.CancelledError, Exception):
  646. pass
  647. async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
  648. """Get information about a chat/room.
  649. BasePlatformAdapter override
  650. """
  651. name = self._room_names.get(chat_id, chat_id)
  652. kind = self._room_kinds.get(chat_id, "")
  653. chat_type = "dm" if kind == "ROOM_KIND_DM" else "group"
  654. return {
  655. "name": name,
  656. "type": chat_type,
  657. }
  658. # ------------------------------------------------------------------ #
  659. # Reactions
  660. # ------------------------------------------------------------------ #
  661. @staticmethod
  662. def _emoji_to_shortcode(emoji: str) -> str:
  663. """Convert a unicode emoji to a Chatto shortcode name.
  664. If the emoji is already a shortcode (no unicode mapping found),
  665. return it as-is.
  666. """
  667. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  668. if shortcode:
  669. return shortcode
  670. # Already a shortcode like "thumbsup" — return as-is
  671. return emoji
  672. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  673. """Add a reaction to a message via MessageService/AddReaction."""
  674. shortcode = self._emoji_to_shortcode(emoji)
  675. try:
  676. try:
  677. client = await self._require_client()
  678. except RuntimeError:
  679. logger.warning("Chatto: AddReaction — client unavailable")
  680. return False
  681. result = await client.add_reaction(
  682. room_id=room_id,
  683. message_event_id=message_id,
  684. emoji=shortcode,
  685. )
  686. return result
  687. except ChattoError as e:
  688. logger.warning("Chatto: AddReaction failed: %s", e)
  689. return False
  690. except Exception as e:
  691. logger.warning("Chatto: AddReaction error: %s", e)
  692. return False
  693. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  694. """Remove a reaction from a message via MessageService/RemoveReaction."""
  695. shortcode = self._emoji_to_shortcode(emoji)
  696. try:
  697. try:
  698. client = await self._require_client()
  699. except RuntimeError:
  700. logger.warning("Chatto: RemoveReaction — client unavailable")
  701. return False
  702. result = await client.remove_reaction(
  703. room_id=str(chat_id),
  704. message_event_id=str(message_id),
  705. emoji=shortcode,
  706. )
  707. return result
  708. except ChattoError as e:
  709. logger.warning("Chatto: RemoveReaction failed: %s", e)
  710. return False
  711. except Exception as e:
  712. logger.warning("Chatto: RemoveReaction error: %s", e)
  713. return False
  714. # ------------------------------------------------------------------ #
  715. # DM initiation (Chatto-unique)
  716. # ------------------------------------------------------------------ #
  717. async def start_dm(self, user_id: str) -> Optional[str]:
  718. """Start a direct message with a user via RoomService/StartDM.
  719. Returns the room ID on success, or None on failure.
  720. """
  721. if not user_id:
  722. return None
  723. try:
  724. try:
  725. client = await self._require_client()
  726. except RuntimeError:
  727. return None
  728. room = await client.start_dm(participant_ids=[str(user_id)])
  729. self._room_names[room.id] = room.name
  730. self._room_kinds[room.id] = room.kind
  731. return room.id
  732. except ChattoError as e:
  733. logger.debug("Chatto: StartDM failed: %s", e)
  734. return None
  735. except Exception as e:
  736. logger.debug("Chatto: StartDM error: %s", e)
  737. return None
  738. # ------------------------------------------------------------------ #
  739. # Room creation (Chatto-unique)
  740. # ------------------------------------------------------------------ #
  741. async def create_room(
  742. self,
  743. name: str,
  744. description: str = "",
  745. group_id: str = "",
  746. universal: bool = True,
  747. ) -> Optional[str]:
  748. """Create an ad-hoc room via RoomService/CreateRoom.
  749. Returns the room ID on success, or None on failure.
  750. """
  751. try:
  752. try:
  753. client = await self._require_client()
  754. except RuntimeError:
  755. return None
  756. room = await client.create_room(
  757. name=name,
  758. group_id=group_id or "",
  759. description=description,
  760. universal=universal,
  761. )
  762. rid = str(room.id) if room else ""
  763. if rid:
  764. self._room_names[rid] = room.name
  765. self._room_kinds[rid] = room.kind
  766. return rid
  767. logger.debug("Chatto: CreateRoom returned no room id")
  768. return None
  769. except ChattoError as e:
  770. logger.debug("Chatto: CreateRoom failed: %s", e)
  771. return None
  772. except Exception as e:
  773. logger.debug("Chatto: CreateRoom error: %s", e)
  774. return None
  775. # ------------------------------------------------------------------ #
  776. # Processing lifecycle hooks (reactions-based, like Discord)
  777. # ------------------------------------------------------------------ #
  778. def _event_room_and_message_id(self, event: MessageEvent) -> Tuple[str, str]:
  779. """Extract room_id and message_id from a MessageEvent."""
  780. message_id = event.message_id or ""
  781. chat_id = event.source.chat_id
  782. return chat_id, message_id
  783. async def on_processing_start(self, event: MessageEvent) -> None:
  784. """Add an 👀 (eyes) reaction to the incoming message.
  785. BasePlatformAdapter override
  786. """
  787. logger.info("self.chatto_config.reactions.value: %s", self.chatto_config.reactions.value)
  788. if not self.chatto_config.reactions.value:
  789. return
  790. chat_id, message_id = self._event_room_and_message_id(event)
  791. if not chat_id or not message_id:
  792. logger.warning("Chatto: on_processing_start — empty chat_id or message_id, skipping reaction")
  793. return
  794. await self.add_reaction(chat_id, message_id, "👀")
  795. async def on_processing_complete(
  796. self, event: MessageEvent, outcome: ProcessingOutcome
  797. ) -> None:
  798. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  799. BasePlatformAdapter override
  800. """
  801. if not self.chatto_config.reactions.value:
  802. return
  803. chat_id, message_id = self._event_room_and_message_id(event)
  804. if not chat_id or not message_id:
  805. return
  806. # Remove the processing eyes reaction
  807. await self.remove_reaction(chat_id, message_id, "👀")
  808. # Add the outcome reaction
  809. if outcome == ProcessingOutcome.SUCCESS:
  810. await self.add_reaction(chat_id, message_id, "✅")
  811. elif outcome == ProcessingOutcome.FAILURE:
  812. await self.add_reaction(chat_id, message_id, "❌")
  813. # ------------------------------------------------------------------ #
  814. # Asset upload (chunked)
  815. # ------------------------------------------------------------------ #
  816. async def _upload_asset(self, room_id: str, file_path: str) -> Optional[str]:
  817. """Upload a file via the chunked AssetUploadService.
  818. Returns the asset ID on success, or None on failure.
  819. """
  820. try:
  821. with open(file_path, "rb") as f:
  822. file_data = f.read()
  823. except Exception as e:
  824. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  825. return None
  826. if not file_data:
  827. logger.error("Chatto: file %s is empty", file_path)
  828. return None
  829. file_size = len(file_data)
  830. file_name = os.path.basename(file_path)
  831. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  832. sha256_hash = hashlib.sha256(file_data).hexdigest()
  833. try:
  834. try:
  835. client = await self._require_client()
  836. except RuntimeError:
  837. logger.error("Chatto: upload aborted - no client available")
  838. return None
  839. # Step 1: Create upload session
  840. upload = await client.create_upload(
  841. room_id=room_id,
  842. filename=file_name,
  843. size=file_size,
  844. sha256=sha256_hash,
  845. content_type=mime_type,
  846. )
  847. upload_id = str(getattr(cast(Any, upload), "id", ""))
  848. if not upload_id:
  849. logger.error("Chatto: CreateUpload returned no upload ID")
  850. return None
  851. # Step 2: Upload chunks
  852. offset = 0
  853. while offset < file_size:
  854. chunk = file_data[offset:offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  855. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  856. await client.upload_chunk(
  857. upload_id=upload_id,
  858. offset=offset,
  859. content=chunk,
  860. chunk_sha256=chunk_sha256,
  861. )
  862. offset += len(chunk)
  863. # Step 3: Complete upload
  864. upload, asset = await client.complete_upload(upload_id=upload_id)
  865. if not asset:
  866. logger.error("Chatto: CompleteUpload returned no asset")
  867. return None
  868. asset_id = str(getattr(cast(Any, asset), "id", ""))
  869. logger.info("Chatto: uploaded %s as asset %s (%d bytes)", file_name, asset_id, file_size)
  870. return asset_id
  871. except ChattoError as e:
  872. logger.error("Chatto: upload failed: %s", e)
  873. return None
  874. except Exception as e:
  875. logger.error("Chatto: upload error: %s", e)
  876. return None
  877. async def send_image_file(
  878. self,
  879. chat_id: str,
  880. file_path: str,
  881. caption: Optional[str] = None,
  882. reply_to: Optional[str] = None,
  883. metadata: Optional[Dict[str, Any]] = None,
  884. ) -> SendResult:
  885. """Send a local image file via the chunked upload API. Do not change signature.
  886. BasePlatformAdapter override
  887. """
  888. # Validate the path is safe
  889. safe_path = self.validate_media_delivery_path(file_path)
  890. if not safe_path:
  891. logger.warning("Chatto: send_image_file — unsafe path %s", file_path)
  892. text = "⚠️ Couldn't deliver the image attachment."
  893. if caption:
  894. text = f"{caption}\n{text}"
  895. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  896. asset_id = await self._upload_asset(str(chat_id), safe_path)
  897. if not asset_id:
  898. # Fallback to a notice
  899. text = "⚠️ Couldn't deliver the image attachment."
  900. if caption:
  901. text = f"{caption}\n{text}"
  902. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  903. thread_id = (metadata or {}).get("thread_id")
  904. if reply_to:
  905. thread_id = reply_to
  906. try:
  907. try:
  908. client = await self._require_client()
  909. except RuntimeError:
  910. return SendResult(success=False, error="Chatto client not available", retryable=True)
  911. msg = await client.post_message(
  912. room_id=str(chat_id),
  913. body=caption or "",
  914. attachment_asset_ids=[asset_id],
  915. thread_root_event_id=str(thread_id) if thread_id else "",
  916. )
  917. self._mark_seen(msg.id)
  918. return SendResult(success=True, message_id=msg.id, raw_response=msg)
  919. except ChattoError as e:
  920. return SendResult(success=False, error=str(e), retryable=True)
  921. except Exception as e:
  922. return SendResult(success=False, error=str(e), retryable=False)
  923. async def send_image(
  924. self,
  925. chat_id: str,
  926. image_url: str,
  927. caption: Optional[str] = None,
  928. reply_to: Optional[str] = None,
  929. metadata: Optional[Dict[str, Any]] = None,
  930. ) -> SendResult:
  931. """Send an image to a Chatto room.
  932. Tries to download the image from the URL and upload it as a native
  933. attachment. Falls back to sending the URL as a link (Chatto renders
  934. link previews) if the download fails.
  935. BasePlatformAdapter override
  936. """
  937. # Try downloading and uploading as attachment
  938. try:
  939. import tempfile
  940. import urllib.request as _urllib_request
  941. # Download to a temp file
  942. parsed = urlsplit(image_url)
  943. url_path = parsed.path
  944. ext = os.path.splitext(url_path)[1] or ".png"
  945. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  946. try:
  947. os.close(tmp_fd)
  948. req = _urllib_request.Request(image_url, headers={"User-Agent": "Hermes/1.0"})
  949. try:
  950. import ssl
  951. ctx = ssl.create_default_context()
  952. except Exception:
  953. ctx = None
  954. with _urllib_request.urlopen(req, timeout=ChattoConstants.HTTP_TIMEOUT, context=ctx) as resp:
  955. with open(tmp_path, "wb") as f:
  956. f.write(resp.read())
  957. # Upload as attachment
  958. result = await self.send_image_file(
  959. chat_id, tmp_path, caption=caption,
  960. reply_to=reply_to, metadata=metadata,
  961. )
  962. if result.success:
  963. return result
  964. finally:
  965. try:
  966. os.unlink(tmp_path)
  967. except OSError:
  968. pass
  969. except Exception as e:
  970. logger.debug("Chatto: send_image download/upload failed, falling back to link: %s", e)
  971. # Fallback: send as link (Chatto renders link previews)
  972. text = image_url
  973. if caption:
  974. text = f"{caption}\n{image_url}"
  975. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  976. # ---------------------------------------------------------------------------
  977. # Cron / out-of-process delivery
  978. # ---------------------------------------------------------------------------
  979. async def hermes_standalone_sender_fn(
  980. pconfig,
  981. chat_id,
  982. message,
  983. *,
  984. thread_id=None,
  985. media_files=None,
  986. force_document=False,
  987. ) -> SendResult:
  988. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  989. Used by cron / scheduled routines that run out-of-process. Creates a
  990. short-lived chattolib client, posts, and closes.
  991. """
  992. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  993. # Create a temporary client for standalone sending
  994. client: ChattoClient
  995. 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):
  996. return SendResult(success=False, error="Chatto: base URL or credentials missing")
  997. try:
  998. if chatto_config.token.value:
  999. client = ChattoClient(base_url=chatto_config.base_url.value, token=chatto_config.token.value)
  1000. else:
  1001. if chatto_config.login.value and chatto_config.password.value:
  1002. client = await ChattoClient.login(
  1003. base_url=chatto_config.base_url.value, login=chatto_config.login.value, password=chatto_config.password.value,
  1004. )
  1005. except (Exception, ValueError) as exc:
  1006. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  1007. finally:
  1008. logger.debug("Chatto standalone client: {client}")
  1009. try:
  1010. kwargs: Dict[str, Any] = {}
  1011. if chatto_config.auto_thread.value and thread_id:
  1012. kwargs["in_reply_to"] = thread_id
  1013. if media_files and media_files.get("attachment_asset_ids"):
  1014. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  1015. try:
  1016. posted = await client.post_message(chat_id, message, **kwargs)
  1017. except Exception as exc:
  1018. return SendResult(success=False, error=str(exc))
  1019. return SendResult(success=True, message_id=getattr(posted, "id", "") or None)
  1020. finally:
  1021. try:
  1022. await client.close()
  1023. except Exception as exc:
  1024. logger.error("Chatto standalone: error closing short-lived client. Perhaps already closed. {exc}")
  1025. def hermes_validate_config(config: PlatformConfig) -> bool:
  1026. """"
  1027. Function name should be the same as register argument name with "hermes_" prefix, so we
  1028. know that it is needed for plugin register(). Do not change signature.
  1029. - config
  1030. Check whether Chatto Plugin is configured. Compare to hermes_is_connected()."""
  1031. chatto_config = ChattoConfiguration(pconfig=config)
  1032. if len(chatto_config.allowed_users.value) > 0 and chatto_config.allow_all_users.value:
  1033. logger.info("Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both.")
  1034. return False
  1035. if chatto_config.base_url.value:
  1036. if (chatto_config.token.value is not None) or (chatto_config.login.value and chatto_config.password.value):
  1037. return True
  1038. else:
  1039. logger.error("Chatto: Minimally, either token or login/password must be set.")
  1040. else:
  1041. logger.error("Chatto: base_url must be set.")
  1042. return False
  1043. def hermes_check_fn() -> bool:
  1044. """Check if Chatto is configured and dependencies are available.
  1045. Add real logic?! Or just .. there are no dependencies.. always return true. Really. Docs suck."""
  1046. try:
  1047. import chattolib.client # noqa: F401 — vendored dependency probe
  1048. return True
  1049. except ImportError:
  1050. return False
  1051. # ---------------------------------------------------------------------------
  1052. # is_connected probe
  1053. # ---------------------------------------------------------------------------
  1054. def hermes_is_connected(config: PlatformConfig) -> bool:
  1055. """Check whether Chatto Plugin is connected. But where to? To the Hermes Agent? To Chatto Server?
  1056. The Hermes Agent plugin docs suck and it seems there are many functions to do the same."""
  1057. return bool(hermes_validate_config(config) and config.enabled)
  1058. # ---------------------------------------------------------------------------
  1059. # YAML → env config bridge
  1060. # ---------------------------------------------------------------------------
  1061. @DeprecationWarning
  1062. def hermes_apply_yaml_config_fn(yaml_dict: dict, platform_dict: dict) -> Optional[dict]:
  1063. """Translate config.yaml chatto.extra keys into CHATTO_* env vars.
  1064. I don't actually get why Hermes wants us to modify OS environment variables.
  1065. Bad behavior in my book.
  1066. Also .. I don't think we need this"""
  1067. if not isinstance(platform_dict, dict):
  1068. platform_dict = {}
  1069. extra = platform_dict.get("extra", {}) or {}
  1070. if not isinstance(extra, dict):
  1071. extra = {}
  1072. for yaml_key, env_key in ChattoConstants.EXTRA_ENV_MAPPING.items():
  1073. val = extra.get(yaml_key)
  1074. if val is not None and not os.getenv(env_key):
  1075. if isinstance(val, bool):
  1076. env_val = str(val).lower()
  1077. elif isinstance(val, list):
  1078. env_val = ",".join(str(v) for v in val)
  1079. else:
  1080. env_val = str(val)
  1081. os.environ[env_key] = env_val
  1082. channels = extra.get(ChattoConfiguration.channels.field_name)
  1083. if isinstance(channels, list) and not os.getenv(ChattoConfiguration.channels.env_name):
  1084. os.environ[ChattoConfiguration.channels.env_name] = ",".join(str(c) for c in channels)
  1085. allowed = extra.get(ChattoConfiguration.allowed_users.field_name)
  1086. if isinstance(allowed, list) and not os.getenv(ChattoConfiguration.allowed_users.env_name):
  1087. os.environ[ChattoConfiguration.allowed_users.env_name] = ",".join(str(u) for u in allowed)
  1088. if ChattoConfiguration.allow_all_users.field_name in extra and not os.getenv(ChattoConfiguration.allow_all_users.env_name):
  1089. os.environ[ChattoConfiguration.allow_all_users.env_name] = str(extra[ChattoConfiguration.allow_all_users.field_name]).lower()
  1090. return None
  1091. def hermes_setup_fn() -> None:
  1092. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  1093. Function name should be the same as register argument name with "hermes_" prefix, so we
  1094. know that it is needed for plugin register().
  1095. """
  1096. from hermes_cli.setup import (
  1097. prompt,
  1098. prompt_yes_no,
  1099. save_env_value,
  1100. get_env_value,
  1101. print_header,
  1102. print_info,
  1103. print_warning,
  1104. print_success,
  1105. )
  1106. url = prompt(
  1107. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:")
  1108. if url:
  1109. save_env_value(ChattoConfiguration.base_url.env_name, url)
  1110. login = prompt("Chatto login (username):")
  1111. if login:
  1112. save_env_value(ChattoConfiguration.login.env_name, login)
  1113. password = prompt("Chatto password:", password=True)
  1114. if password:
  1115. save_env_value(ChattoConfiguration.password.env_name, password)
  1116. channels = prompt("Room IDs to watch (comma-separated, or empty for all):")
  1117. if channels:
  1118. save_env_value(ChattoConfiguration.channels.env_name, channels)
  1119. home = prompt("Home room ID for notifications (or empty):")
  1120. if home:
  1121. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  1122. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  1123. if allow_all:
  1124. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  1125. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  1126. def hermes_env_enablement_fn() -> Optional[dict]:
  1127. """Seed PlatformConfig.extra from env vars.
  1128. Returns a dict compatible with the PlatformConfig merge hook (or None
  1129. when no env-provided values are present).
  1130. Called by the platform registry during load_gateway_config().
  1131. Return None when the platform isn't minimally configured — the
  1132. caller then skips auto-enabling. Return a dict to seed extras.
  1133. The special 'home_channel' key is extracted and becomes a proper
  1134. HomeChannel dataclass on the PlatformConfig; every other key is
  1135. merged into PlatformConfig.extra.
  1136. Function name should be the same as register argument name with "hermes_" prefix, so we
  1137. know that it is needed for plugin register().
  1138. """
  1139. def _add_env_to_seed(seed: dict, our_key: str) -> dict:
  1140. env_value = os.getenv(our_key.upper())
  1141. if env_value:
  1142. seed[our_key.lower()] = env_value
  1143. return seed
  1144. seed = {}
  1145. seed["base_url"] = (os.getenv(ChattoConfiguration.base_url.env_name) or ChattoClient.DEFAULT_BASE_URL).strip()
  1146. seed = _add_env_to_seed(seed, ChattoConfiguration.token.env_name)
  1147. seed = _add_env_to_seed(seed, ChattoConfiguration.login.env_name)
  1148. seed = _add_env_to_seed(seed, ChattoConfiguration.password.env_name)
  1149. seed = _add_env_to_seed(seed, ChattoConfiguration.channels.env_name)
  1150. seed = _add_env_to_seed(seed, ChattoConfiguration.home_channel.env_name)
  1151. seed = _add_env_to_seed(seed, ChattoConfiguration.require_mention.env_name)
  1152. seed = _add_env_to_seed(seed, ChattoConfiguration.free_response_channels_list.env_name)
  1153. seed = _add_env_to_seed(seed, ChattoConfiguration.auto_thread.env_name)
  1154. logger.debug("seed: " + str(seed))
  1155. return seed
  1156. # ---------------------------------------------------------------------------
  1157. # Plugin registration entry point
  1158. # ---------------------------------------------------------------------------
  1159. def register(ctx) -> None:
  1160. """Plugin entry point — called by the Hermes plugin system."""
  1161. logger.info("Registering Chatto platform plugin on Hermes Agent")
  1162. logger.info("ChattoConfiguration.allowed_users.env_name: %s", ChattoConfiguration.allowed_users.env_name)
  1163. ctx.register_platform(
  1164. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  1165. label=ChattoConstants.PLATFORM_LABEL,
  1166. adapter_factory=hermes_adapter_factory,
  1167. check_fn=hermes_check_fn,
  1168. validate_config=hermes_validate_config,
  1169. is_connected=hermes_is_connected,
  1170. install_hint=ChattoConstants.INSTALL_HINT,
  1171. env_enablement_fn=hermes_env_enablement_fn,
  1172. setup_fn=hermes_setup_fn,
  1173. apply_yaml_config_fn=hermes_apply_yaml_config_fn,
  1174. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  1175. standalone_sender_fn=hermes_standalone_sender_fn,
  1176. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  1177. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  1178. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  1179. emoji="💬",
  1180. allow_update_command=True,
  1181. pii_safe=False,
  1182. platform_hint=(
  1183. "You are chatting in Chatto (a self-hosted or cloud-hosted team or community chat server). "
  1184. "Markdown is supported. Users _may_ address you by @-mentioning your name. If configured, " \
  1185. "you also react without a @-mention. Direct messages reach you without a mention."
  1186. "Keep responses conversational."
  1187. ),
  1188. )