adapter.py 54 KB

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