adapter.py 55 KB

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