adapter.py 54 KB

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