adapter.py 54 KB

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