adapter.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  1. """
  2. Chatto Platform Adapter for Hermes Agent.
  3. A plugin-based gateway adapter that connects to a Chatto server
  4. (self-hosted team chat) and relays messages to/from the Hermes agent.
  5. The adapter uses the chattolib library for all Chatto API interactions,
  6. including both outbound messaging and realtime WebSocket connections.
  7. """
  8. from __future__ import annotations
  9. import inspect
  10. import random
  11. from gateway.platforms.helpers import MessageDeduplicator
  12. # Put the vendored dependencies for THIS platform on sys.path before importing
  13. # anything from chattolib. Imported relatively as part of the plugin package and
  14. # absolutely when this module is loaded standalone (e.g. by the tests).
  15. try:
  16. from .vendor_path import setup_vendor_path
  17. except ImportError: # pragma: no cover - depends on how the module is loaded
  18. from vendor_path import setup_vendor_path
  19. setup_vendor_path()
  20. import asyncio
  21. import hashlib
  22. import logging
  23. import mimetypes
  24. import os
  25. from datetime import datetime, timezone
  26. from typing import Any, Dict, List, Literal, Optional, Tuple, cast
  27. from urllib.parse import urlsplit
  28. logger = logging.getLogger(__name__)
  29. from gateway.platforms.base import (
  30. BasePlatformAdapter,
  31. SendResult,
  32. MessageEvent,
  33. MessageType,
  34. ProcessingOutcome,
  35. cache_media_bytes,
  36. get_inbound_media_max_bytes,
  37. validate_inbound_media_size,
  38. )
  39. from gateway.config import Platform, PlatformConfig
  40. # Chattolib imports (vendored)
  41. # Using vendored chattolib from vendor/chattolib/
  42. # See vendor_chattolib.sh for how to update the vendored copy
  43. # Absolute imports — vendor/ is on sys.path (see above) and chattolib's own
  44. # modules import each other absolutely. Mixing in relative ".vendor.chattolib"
  45. # imports would load a second, distinct copy of every module, so isinstance()
  46. # checks across the two copies would silently fail.
  47. try:
  48. from chattolib.client import (
  49. ChattoClient,
  50. )
  51. from chattolib.exceptions import (
  52. ChattoAuthError,
  53. ChattoError,
  54. )
  55. from chattolib.realtime import (
  56. ChattoRealtimeError,
  57. ChattoRealtimeCloseError, RealtimeEvent,
  58. stream_events
  59. )
  60. from chattolib.realtime_types import (
  61. MessagePostedPayload,
  62. ReactionPayload,
  63. )
  64. from chattolib.types import (
  65. PresenceStatus, RoomKind, User
  66. )
  67. except ImportError as e:
  68. # Fail loudly: continuing here only defers the failure to a confusing
  69. # NameError somewhere deep in the adapter.
  70. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  71. raise
  72. try:
  73. from .platform_config import (
  74. ChattoConfiguration, ChattoConstants,
  75. )
  76. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  77. from platform_config import (
  78. ChattoConfiguration, ChattoConstants,
  79. )
  80. # --------------------------------------------------------------------------- #
  81. # Adapter
  82. # --------------------------------------------------------------------------- #
  83. def hermes_adapter_factory(config: PlatformConfig):
  84. """Factory wrapper that constructs ChattoAdapter from a PlatformConfig."""
  85. return ChattoAdapter(config)
  86. class ChattoAdapter(BasePlatformAdapter):
  87. """Chatto platform adapter — receives messages via WebSocket realtime,
  88. sends via ConnectRPC."""
  89. _SPLIT_THRESHOLD = 9900
  90. # Read by BasePlatformAdapter.max_message_length_for_chat(), which the
  91. # gateway and the stream consumer use to chunk outgoing messages. Without
  92. # it they fall back to 4096 and split Chatto messages far earlier than
  93. # necessary — send() itself already truncates at 10000.
  94. MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  95. splits_long_messages = True
  96. supports_code_blocks: bool = True
  97. supports_status_text: bool = True # client.update_custom_status
  98. def __init__(self, pconfig: PlatformConfig):
  99. """Signature needs to be compatible with BasePlatformAdapter.__init__ """
  100. super().__init__(config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME))
  101. # "extra" has been pre-processed by Hermes-Framework to be a dict of extra config values insode PlatformConfig.
  102. # --- Configuration from our configuration data class with some logic ---
  103. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  104. # ------ State -------
  105. # SDK runtime handle (injected by Hermes); annotate for Pylance
  106. self.sdk: Any = getattr(self, "sdk", None)
  107. # Our own user, filled in by connect(). Events arriving before connect()
  108. # completes must not blow up on an undefined attribute.
  109. self.me: Optional[User] = None
  110. # --- Runtime state ---
  111. self._user_id: str = ""
  112. self._user_display: str = ""
  113. self._room_names: Dict[str, str] = {}
  114. self._room_kinds: Dict[str, RoomKind] = {}
  115. self._our_thread_roots: set = set() # thread root event IDs we created
  116. self._our_message_ids: set = set() # message IDs we sent (for thread root detection)
  117. self._seen: list[str] = [] # Plain RealtimeEvent-id list
  118. self._resume_cursor: Optional[str] = None
  119. self._watch_room_ids: List[str] = []
  120. self._ws_task: Optional[asyncio.Task] = None
  121. self._ws_ready: Optional[asyncio.Event] = None
  122. self._ws_active = False
  123. self._ws_ref = None # reference to open websocket for dynamic resubscribe
  124. # Persistent typing indicator loops per room
  125. self._typing_tasks: Dict[str, asyncio.Task] = {}
  126. # Member directory cache: user_id -> user info dict
  127. self._user_cache: Dict[str, User] = {}
  128. # Chattolib client cache and lock for async access.
  129. self._chatto_client: Optional[ChattoClient] = None
  130. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  131. # Dedup — chattolib may redeliver events across reconnects.
  132. self._dedup = MessageDeduplicator()
  133. def _list_functions(self):
  134. for name, member in inspect.getmembers(self, predicate=callable):
  135. # filtert dunder-Methoden falls gewünscht
  136. if not name.startswith('__'):
  137. logger.info("functions: %s", name)
  138. # ------------------------------------------------------------------ #
  139. # Auth
  140. # ------------------------------------------------------------------ #
  141. async def _get_chatto_client(self: ChattoAdapter) -> Optional[ChattoClient]:
  142. """Get or create a ChattoClient instance."""
  143. if self._chatto_client is not None:
  144. return self._chatto_client
  145. async with self._chatto_client_lock:
  146. if self._chatto_client is not None:
  147. return self._chatto_client
  148. try:
  149. assert(self.chatto_config.login.value) # now we can assume, _login is available.
  150. client = await self._open_client(
  151. base_url=self.chatto_config.base_url.value,
  152. login=self.chatto_config.login.value,
  153. password=self.chatto_config.password.value,
  154. token=self.chatto_config.token.value,
  155. )
  156. self._chatto_client = client
  157. self._token = client.token
  158. logger.info("Chatto: logged in as '%s' via chattolib", self.chatto_config.login.value)
  159. return client
  160. except ChattoAuthError as e:
  161. logger.error("Chatto: authentication failed: %s", e)
  162. return None
  163. except (ChattoError, ValueError) as e:
  164. logger.error("Chatto: failed to create client: %s", e)
  165. return None
  166. async def _require_client(self) -> ChattoClient:
  167. """Return a ChattoClient or raise RuntimeError if unavailable.
  168. Use this helper when the caller expects a client to exist and
  169. wants a single canonical failure path. Methods that prefer a
  170. soft-fail can catch RuntimeError and return gracefully.
  171. """
  172. client = await self._get_chatto_client()
  173. if client is None:
  174. raise RuntimeError("Chatto client unavailable")
  175. return client
  176. async def _ensure_token(self) -> bool:
  177. """Ensure we have a logged-in Chatto client and token."""
  178. if self.chatto_config.token.value and isinstance(self._chatto_client, ChattoClient):
  179. return True
  180. client = await self._get_chatto_client()
  181. return client is not None
  182. async def _relogin(self) -> bool:
  183. """Force re-login (token expired)."""
  184. self._token = None
  185. return await self._ensure_token()
  186. # ------------------------------------------------------------------ #
  187. # Connection
  188. # ------------------------------------------------------------------ #
  189. async def _open_client(
  190. self,
  191. *,
  192. base_url: str,
  193. login: str,
  194. password: str,
  195. token: Optional[str] = None,
  196. ) -> ChattoClient:
  197. """Return a connected ``ChattoClient`` using token or login/password."""
  198. if token:
  199. return ChattoClient(token=token, base_url=base_url)
  200. return await ChattoClient.login(login, password, base_url=base_url)
  201. async def connect(self, *, is_reconnect: bool = False) -> bool:
  202. """Connect to Chatto and start the realtime event stream.
  203. BasePlatformAdapter override
  204. """
  205. logger.info("Chatto: connecting...")
  206. if not await self._ensure_token():
  207. return False
  208. try:
  209. client = await self._require_client()
  210. except RuntimeError:
  211. self._set_fatal_error("connect_failed", "Chatto client not available", retryable=True)
  212. return False
  213. # Get our first own user info
  214. try:
  215. self.me = await client.me()
  216. except Exception as exc:
  217. logger.error("Chatto: failed to get user info: %s", exc)
  218. self._set_fatal_error(
  219. "chatto_auth_failed",
  220. f"Chatto auth failed: {exc}",
  221. retryable=False,
  222. )
  223. try:
  224. assert(self._chatto_client)
  225. await self._chatto_client.close()
  226. finally:
  227. self._chatto_client = None
  228. return False
  229. # Broadcast online presence so the bot appears online in the member list
  230. try:
  231. await client.update_presence(status=PresenceStatus.ONLINE)
  232. except Exception:
  233. logger.debug("Chatto: update_presence(online) failed on connect", exc_info=True)
  234. self._closing = False
  235. # Start background realtime WS event stream loop.
  236. self._ws_ready = asyncio.Event()
  237. self._ws_task = asyncio.create_task(
  238. self._chattolib_event_loop(), name="chatto-event-stream",
  239. )
  240. self._mark_connected()
  241. self._list_functions()
  242. logger.info(
  243. "Chatto: connected and authentiated to %s using login:'%s' (display_name:'%s' id: '%s')",
  244. self.chatto_config.base_url.value,
  245. self.me.login, self.me.display_name, self.me.id
  246. )
  247. return True
  248. async def disconnect(self) -> None:
  249. """Stop WebSocket, liveness probe, typing tasks, and clear state.
  250. BasePlatformAdapter override
  251. """
  252. # Broadcast offline presence before tearing down
  253. try:
  254. client = await self._require_client()
  255. await client.update_presence(status=PresenceStatus.OFFLINE)
  256. except Exception:
  257. logger.debug("Chatto: update_presence(PresenceStatus.OFFLINE) failed on disconnect", exc_info=True)
  258. self._ws_active = False
  259. self._closing = True
  260. # Cancel all typing tasks
  261. for chat_id in list(self._typing_tasks.keys()):
  262. await self.stop_typing(chat_id)
  263. if self._ws_task and not self._ws_task.done():
  264. self._ws_task.cancel()
  265. try:
  266. await self._ws_task
  267. except (asyncio.CancelledError, Exception):
  268. pass
  269. self._ws_task = None
  270. if self._chatto_client:
  271. try:
  272. await self._chatto_client.close()
  273. except Exception:
  274. logger.exception("Chatto: error closing client")
  275. finally:
  276. self._chatto_client = None
  277. self._token = None
  278. logger.info("Chatto: disconnected")
  279. self._mark_disconnected()
  280. async def _seed_room(self, room_id: str) -> None:
  281. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  282. try:
  283. try:
  284. client = await self._require_client()
  285. timeline_page = await client.get_room_events(room_id)
  286. except RuntimeError:
  287. logger.debug("Chatto: _seed_room aborted - no client available for %s", room_id)
  288. return
  289. for ev in timeline_page.events:
  290. if ev.id:
  291. self._mark_seen(ev.id)
  292. logger.debug("Chatto: seeded room %s with %d events", room_id, len(timeline_page.events))
  293. except Exception as e:
  294. logger.debug("Chatto: get room events failed for %s: %s", room_id, e)
  295. # ------------------------------------------------------------------ #
  296. # Realtime Event List
  297. # ------------------------------------------------------------------ #
  298. def _mark_seen(self, event_id: str) -> None:
  299. self._seen.append(event_id)
  300. while len(self._seen) > ChattoConstants.SEEN_CAP:
  301. self._seen.remove(self._seen[0]) # fastest removal of first item in a list.
  302. def _is_seen(self, event_id: str) -> bool:
  303. return event_id in self._seen
  304. # ------------------------------------------------------------------ #
  305. # WebSocket Realtime Transport
  306. # ------------------------------------------------------------------ #
  307. def _check_auth(self, user: User) -> bool:
  308. """We roll our own auth-systen on the against the chatto_config'ured allowed_users etc.
  309. because.. Hermes authz_mixin.py IS NOT SANE.
  310. """
  311. if self.chatto_config.allow_all_users.value:
  312. return True
  313. if user.login in self.chatto_config.allowed_users.value:
  314. return True
  315. if user.id in self.chatto_config.allowed_users.value:
  316. return True
  317. logger.info("Chatto: rejecting message from unauthorized user '%s' (%s)", user.login, user.id)
  318. return False
  319. # ------------------------------------------------------------------ #
  320. # Inbound attachments
  321. # ------------------------------------------------------------------ #
  322. async def _download_attachment_bytes(self, url: str) -> bytes:
  323. """Download an attachment, refusing to buffer more than the gateway cap.
  324. The Content-Length header is checked first so an oversized asset is
  325. rejected before a single chunk is read; the running total is re-checked
  326. as chunks arrive, because a missing or lying header must not smuggle an
  327. unbounded body past the cap.
  328. """
  329. import httpx
  330. max_bytes = get_inbound_media_max_bytes()
  331. chunks: List[bytes] = []
  332. total = 0
  333. async with httpx.AsyncClient(
  334. timeout=ChattoConstants.HTTP_TIMEOUT, follow_redirects=True,
  335. ) as http:
  336. async with http.stream("GET", url) as resp:
  337. resp.raise_for_status()
  338. declared = resp.headers.get("content-length")
  339. if declared:
  340. try:
  341. declared_size = int(declared)
  342. except ValueError:
  343. logger.debug("Chatto: ignoring invalid Content-Length %r", declared)
  344. else:
  345. validate_inbound_media_size(
  346. declared_size, media_type="attachment", max_bytes=max_bytes,
  347. )
  348. async for chunk in resp.aiter_bytes():
  349. total += len(chunk)
  350. validate_inbound_media_size(
  351. total, media_type="attachment", max_bytes=max_bytes,
  352. )
  353. chunks.append(chunk)
  354. return b"".join(chunks)
  355. async def _cache_attachments(
  356. self, room_id: str, attachments: List[Any],
  357. ) -> Tuple[List[str], List[str], List[str]]:
  358. """Download message attachments into the gateway media cache.
  359. Returns ``(media_urls, media_types, media_kinds)`` — the paths are
  360. agent-visible cache paths, exactly what ``cache_media_bytes`` yields for
  361. every other platform. A failing attachment is logged and skipped: the
  362. message itself still reaches the agent.
  363. """
  364. media_urls: List[str] = []
  365. media_types: List[str] = []
  366. media_kinds: List[str] = []
  367. for att in attachments or []:
  368. asset_url = getattr(att, "asset_url", None)
  369. url = getattr(asset_url, "url", "") if asset_url else ""
  370. filename = getattr(att, "filename", "") or ""
  371. content_type = getattr(att, "content_type", "") or ""
  372. if not url:
  373. # Videos are announced before transcoding finishes, so the
  374. # signed URL can legitimately be missing on arrival.
  375. logger.info(
  376. "Chatto: attachment '%s' has no asset URL yet, skipping", filename,
  377. )
  378. continue
  379. try:
  380. data = await self._download_attachment_bytes(url)
  381. cached = cache_media_bytes(
  382. data, filename=filename, mime_type=content_type,
  383. )
  384. except Exception as e:
  385. logger.warning(
  386. "Chatto: failed to cache attachment '%s' (%s): %s",
  387. filename, content_type, e,
  388. )
  389. continue
  390. if cached is None:
  391. logger.warning(
  392. "Chatto: attachment '%s' (%s) could not be cached, skipping",
  393. filename, content_type,
  394. )
  395. continue
  396. media_urls.append(cached.path)
  397. media_types.append(cached.media_type)
  398. media_kinds.append(cached.kind)
  399. return media_urls, media_types, media_kinds
  400. @staticmethod
  401. def _message_type_for_media_kinds(media_kinds: List[str]) -> MessageType:
  402. """Pick the MessageType for a set of cached attachment kinds."""
  403. if "document" in media_kinds:
  404. return MessageType.DOCUMENT
  405. if "image" in media_kinds:
  406. return MessageType.PHOTO
  407. if "video" in media_kinds:
  408. return MessageType.VIDEO
  409. if "audio" in media_kinds:
  410. return MessageType.AUDIO
  411. return MessageType.TEXT
  412. async def _dispatch_message_posted(self, payload: MessagePostedPayload) -> None:
  413. try:
  414. client = await self._require_client()
  415. except RuntimeError:
  416. logger.warning("Chatto: chattolib event loop aborted - no client available")
  417. return
  418. logger.info("Chatto WS: 'message_posted' event_payload:%s", payload)
  419. message = await payload.fetch_message(client=client)
  420. if message is None or message.deleted_at:
  421. return
  422. message_body = message.body or ""
  423. attachments = list(message.attachments or [])
  424. # A message carrying only an image/PDF has an empty body — dropping it
  425. # here is what made attachments sent to Hermes disappear silently.
  426. if not message_body and not attachments:
  427. return
  428. if message.actor_id in self._user_cache:
  429. # try the user cache.
  430. user = self._user_cache.get(message.actor_id)
  431. else:
  432. # get the user and update cache.
  433. directory_member = await client.get_user(user_id=message.actor_id)
  434. if directory_member is None:
  435. return
  436. user = directory_member.user
  437. if user is None:
  438. return
  439. self._user_cache[user.id] = user
  440. if user is None:
  441. return
  442. if not self._check_auth(user):
  443. return
  444. # For DMs, always respond. For rooms with require_mention, only respond when mentioned.
  445. # Strip the mention from the text for the agent
  446. # Todo: use a function that either reads from cache or gets room kind again.
  447. if self._room_kinds.get(message.room_id) is None:
  448. room_viewer_state = await client.get_room(message.room_id)
  449. if room_viewer_state is None:
  450. return
  451. if room_viewer_state.room is None:
  452. return
  453. self._room_kinds[message.room_id] = room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  454. room_kind = self._room_kinds.get(message.room_id)
  455. logger.info("message_body: %s room_kind: %s", message_body, room_kind)
  456. mentioned = False
  457. if (room_kind == RoomKind.CHANNEL and self.chatto_config.require_mention.value and self.me):
  458. if self.me.login and not mentioned:
  459. mentioned = bool(f"@{self.me.login}" in message_body)
  460. if self.me.display_name and not mentioned:
  461. mentioned = bool(f"@{self.me.display_name}" in message_body)
  462. if mentioned is False:
  463. logger.debug("Discarding message. Bot was not mentionend but require_mention is '%s'.", self.chatto_config.require_mention.value)
  464. return
  465. logger.info("mentioned: %s", mentioned)
  466. # Thread anchoring — if the incoming message is inside a thread, we
  467. # keep that thread by default; otherwise leave thread_id unset so
  468. # replies land at the root.
  469. thread_id = payload.thread_root_event_id or None
  470. if not thread_id and room_kind != RoomKind.DM and self.chatto_config.auto_thread.value:
  471. thread_id = message.id
  472. source = self.build_source(
  473. chat_id=payload.room_id,
  474. chat_name=self._room_names.get(message.room_id),
  475. 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.,
  476. user_id=message.actor_id,
  477. user_name=user.login, # use login, because display_name is changeable by anyone.
  478. thread_id=thread_id,
  479. message_id=payload.message_event_id,
  480. role_authorized=True,
  481. )
  482. msg_type = MessageType.COMMAND if (message_body.lstrip().startswith("/")) else MessageType.TEXT
  483. my_body = message_body.lstrip() if msg_type == MessageType.COMMAND else message_body
  484. # Attachments — download and hand the local cache paths to the gateway,
  485. # which runs vision enrichment / document extraction off media_urls.
  486. media_urls, media_types, media_kinds = await self._cache_attachments(
  487. payload.room_id, attachments,
  488. )
  489. if media_kinds and msg_type != MessageType.COMMAND:
  490. # Same precedence as the Teams/Signal adapters: document-context
  491. # injection gates strictly on DOCUMENT, image handling keys off the
  492. # per-path image/* MIME regardless of message_type.
  493. msg_type = self._message_type_for_media_kinds(media_kinds)
  494. message_event = MessageEvent(
  495. text=my_body,
  496. source=source,
  497. message_id=message.id,
  498. message_type=msg_type,
  499. media_urls=media_urls,
  500. media_types=media_types,
  501. timestamp=message.created_at or datetime.now(timezone.utc),
  502. raw_message=message,
  503. reply_to_message_id=message.id,
  504. reply_to_text=message_body,
  505. reply_to_author_id=user.id,
  506. reply_to_author_name=user.login,
  507. )
  508. logger.info("Chatto: Dispatching MessageEvent to Hermes: %s", message_event)
  509. await self.handle_message(message_event)
  510. return
  511. async def _forward_reaction(
  512. self, event: RealtimeEvent, payload: ReactionPayload, *, removed: bool,
  513. ) -> None:
  514. """Forward a human reaction to the gateway's reaction hook surface.
  515. The handler is registered by the gateway via ``set_reaction_handler``
  516. and fans out as ``reaction:added`` / ``reaction:removed`` through the
  517. HookRegistry. The dict shape mirrors the Slack adapter's — hook
  518. consumers are written against that contract, not against a per-platform
  519. one. Our own lifecycle reactions (👀/✅/❌) are dropped: forwarding them
  520. would feed the agent its own markers.
  521. """
  522. actor_id = event.actor_id
  523. if actor_id and self.me and actor_id == self.me.id:
  524. return
  525. if not payload.room_id or not payload.message_event_id or not actor_id:
  526. return
  527. handler = getattr(self, "_reaction_handler", None)
  528. if handler is None:
  529. return
  530. action = "removed" if removed else "added"
  531. try:
  532. await handler(
  533. {
  534. "platform": ChattoConstants.PLATFORM_NAME,
  535. "event_name": f"reaction:{action}",
  536. "reaction": payload.emoji,
  537. "user_id": actor_id,
  538. "item_user_id": None,
  539. "item_type": "message",
  540. "channel_id": payload.room_id,
  541. "message_ts": payload.message_event_id,
  542. "event_ts": event.id,
  543. "raw_event": event,
  544. }
  545. )
  546. except Exception: # pragma: no cover - the hook contract is non-blocking
  547. logger.debug("Chatto: reaction hook forwarding failed", exc_info=True)
  548. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  549. if self._is_seen(event.id):
  550. return
  551. if event.actor_id is None:
  552. return
  553. logger.info("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  554. if (event_payload := event.get("message_posted")) is not None:
  555. # Self-event filter — the actor_id on the envelope is authoritative
  556. # (chattolib does NOT filter this itself; see chatto-bridge notes).
  557. actor_id = event.actor_id
  558. if actor_id and self.me and actor_id == self.me.id:
  559. return
  560. await self._dispatch_message_posted(event_payload)
  561. elif event.kind in ("reaction_added", "reaction_removed"):
  562. reaction_payload = event.get(event.kind)
  563. if reaction_payload is not None:
  564. await self._forward_reaction(
  565. event,
  566. cast(ReactionPayload, reaction_payload),
  567. removed=event.kind == "reaction_removed",
  568. )
  569. # confirmed:
  570. elif event.kind in ("mention_notification", "projection_event", "presence_changed", "notification_dismissed",
  571. "room_marked_as_read", "user_typing", "notification_created", "new_direct_message_notification",
  572. "message_edited", "message_retracted"):
  573. logger.debug("Chatto: '%s' event received. Not yet implemented or not needed.", event.kind)
  574. else:
  575. logger.error("Chatto: unknown event kind: '%s'", event.kind)
  576. async def _chattolib_event_loop(self) -> None:
  577. """Event loop using chattolib's stream_events.
  578. This replaces the manual WebSocket loop with chattolib's high-level
  579. stream_events() which provides pre-decoded RealtimeEvent objects.
  580. """
  581. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  582. while not self._closing:
  583. try:
  584. client = await self._require_client()
  585. await self._refresh_rooms()
  586. logger.info("Chatto: starting chattolib event stream with %d rooms", len(self._watch_room_ids))
  587. async for event in stream_events(client):
  588. if self._closing:
  589. return
  590. await self._handle_realtime_event(event)
  591. # Iterator exited cleanly — treat as a normal close and reconnect
  592. # with the local backoff (no server hint available).
  593. logger.info("Chatto: realtime stream ended, reconnecting")
  594. except asyncio.CancelledError:
  595. return
  596. except ChattoRealtimeCloseError as exc:
  597. if not exc.reconnect:
  598. logger.error(
  599. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  600. exc.code, exc.message,
  601. )
  602. return
  603. wait = max(exc.retry_after_ms / 1000.0, ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF)
  604. logger.warning(
  605. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  606. exc.code, wait,
  607. )
  608. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF # server hint supersedes local backoff
  609. await self._sleep_interruptible(wait)
  610. continue
  611. except ChattoRealtimeError as exc:
  612. if getattr(exc, "fatal", False):
  613. logger.error("Chatto: fatal realtime error (%s): %s", exc.code, exc.message)
  614. return
  615. logger.warning(
  616. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  617. exc.code, exc.message, delay,
  618. )
  619. except Exception as exc:
  620. logger.warning(
  621. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  622. exc, delay,
  623. )
  624. if self._closing:
  625. return
  626. jitter = delay * 0.2 * random.random()
  627. await self._sleep_interruptible(delay + jitter)
  628. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  629. async def _sleep_interruptible(self, seconds: float) -> None:
  630. """Sleep in short slices so disconnect() cancels promptly."""
  631. end = asyncio.get_running_loop().time() + seconds
  632. while not self._closing:
  633. remaining = end - asyncio.get_running_loop().time()
  634. if remaining <= 0:
  635. return
  636. await asyncio.sleep(min(remaining, 0.5))
  637. async def _refresh_rooms(self) -> None:
  638. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms."""
  639. try:
  640. client = await self._require_client()
  641. except RuntimeError:
  642. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  643. return
  644. try:
  645. rooms_list = await client.list_rooms()
  646. new_room_ids: List[str] = []
  647. for room_with_state in rooms_list:
  648. if not room_with_state:
  649. continue
  650. room_obj = room_with_state.room or None
  651. if not room_obj:
  652. continue
  653. self._room_names[room_obj.id] = room_obj.name
  654. self._room_kinds[room_obj.id] = room_obj.kind
  655. if room_with_state.viewer_state.is_member and room_obj.id not in self._watch_room_ids:
  656. new_room_ids.append(room_obj.id)
  657. if not new_room_ids:
  658. return
  659. logger.info("Chatto WS: discovered %d new room(s): %s", len(new_room_ids), new_room_ids)
  660. for rid in new_room_ids:
  661. if self._room_kinds.get(rid) != RoomKind.DM:
  662. await client.join_room(rid) # but list_rooms() would not return any if we were not already joined?!
  663. await self._seed_room(rid)
  664. self._watch_room_ids.append(rid)
  665. watch_room_names: list[str] = []
  666. for rid in self._watch_room_ids:
  667. watch_room_names.append(self._room_names[rid] + " (" + rid + ")")
  668. logger.info("Chatto WS: Watching %d room(s): %s", len(self._watch_room_ids), ", ".join(watch_room_names))
  669. except Exception:
  670. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  671. # ------------------------------------------------------------------ #
  672. # Read state & notification dismissal (best-effort, Chatto-unique)
  673. # ------------------------------------------------------------------ #
  674. # Best-effort: mark all watched rooms as read (room_id may be undefined here)
  675. for _rid in list(self._watch_room_ids):
  676. try:
  677. await client.mark_room_as_read(room_id=_rid)
  678. await client.dismiss_all_notifications()
  679. except Exception:
  680. logger.debug("Chatto: mark_room_as_read failed for %s", _rid, exc_info=True)
  681. # ------------------------------------------------------------------ #
  682. # Sending (ConnectRPC — unchanged from polling version)
  683. # ------------------------------------------------------------------ #
  684. async def send(
  685. self,
  686. chat_id: str,
  687. content: str,
  688. reply_to: Optional[str] = None,
  689. metadata: Optional[Dict[str, Any]] = None,
  690. ) -> SendResult:
  691. """Send a message to a Chatto room.
  692. Long messages are split into chunks via ``truncate_message`` and
  693. each chunk is sent as a separate CreateMessage call. The first
  694. chunk's message ID is returned as ``message_id``.
  695. When ``auto_thread`` is enabled and the incoming message was a
  696. regular room message (not already in a thread), the first chunk is
  697. sent as a room message and its ID becomes the thread root. Subsequent
  698. chunks are sent in that thread. This mirrors Discord's auto_thread
  699. behavior.
  700. BasePlatformAdapter override
  701. """
  702. if not content:
  703. return SendResult(success=False, error="Empty message")
  704. formatted = self.format_message(content)
  705. chunks = self.truncate_message(formatted, ChattoConstants.MAX_MESSAGE_LENGTH)
  706. # Thread support — resolve thread_id once
  707. # DM rooms don't support threads, so skip threading for DMs
  708. thread_id = (metadata or {}).get("thread_id")
  709. # Only use reply_to as thread_id if auto_thread is enabled.
  710. # When auto_thread=false, responses go directly in the room
  711. # without threading under the incoming message.
  712. if reply_to and self.chatto_config.auto_thread.value:
  713. # reply_to might be the incoming message ID. If we already have
  714. # thread_id from metadata, keep it (it's the thread root).
  715. # Only use reply_to as thread_id if we don't already have one.
  716. if not thread_id:
  717. thread_id = reply_to
  718. # Check if this is a DM room — DMs don't support threads
  719. room_kind = self._room_kinds.get(chat_id)
  720. is_dm = room_kind == RoomKind.DM
  721. if is_dm:
  722. thread_id = None
  723. # Auto-thread: by default, Chatto creates a thread for replies to room
  724. # messages (not DMs, not already in a thread). This keeps conversations
  725. # organized in the room. Can be disabled via extra.auto_thread=false.
  726. use_auto_thread = self.chatto_config.auto_thread.value and not thread_id and not is_dm
  727. message_ids: List[str] = []
  728. last_resp: Optional[Any] = None
  729. last_error: Optional[str] = None
  730. retryable = False
  731. try:
  732. client = await self._require_client()
  733. except RuntimeError:
  734. return SendResult(success=False, error="Chatto client not available", retryable=True)
  735. for i, chunk in enumerate(chunks):
  736. try:
  737. msg_obj = await client.post_message(
  738. room_id=chat_id,
  739. body=chunk,
  740. thread_root_event_id=str(thread_id) if thread_id else "",
  741. )
  742. except ChattoError as e:
  743. last_error = str(e)
  744. retryable = True
  745. break
  746. except Exception as e:
  747. last_error = str(e)
  748. retryable = True
  749. break
  750. last_resp = msg_obj
  751. self._mark_seen(msg_obj.id)
  752. message_ids.append(msg_obj.id)
  753. self._our_message_ids.add(msg_obj.id)
  754. # If we sent a message WITHOUT a thread_id, this message could
  755. # become a thread root if someone replies to it
  756. if not thread_id:
  757. self._our_thread_roots.add(msg_obj.id)
  758. # Auto-thread: first chunk becomes the thread root,
  759. # subsequent chunks go in the thread
  760. if use_auto_thread and i == 0 and not thread_id:
  761. thread_id = msg_obj.id
  762. # Nothing got through at all — report the failure instead of a phantom success.
  763. if not message_ids:
  764. return SendResult(
  765. success=False,
  766. error=last_error or "Chatto: message could not be sent",
  767. retryable=retryable,
  768. )
  769. first_id = message_ids[0]
  770. # ------------------------------------------------------------------ #
  771. # Thread following (best-effort, Chatto-unique)
  772. # ------------------------------------------------------------------ #
  773. if thread_id:
  774. try:
  775. await client.follow_thread(chat_id, thread_id)
  776. except Exception:
  777. logger.debug("Chatto: follow_thread failed for %s/%s", chat_id, thread_id, exc_info=True)
  778. # A later chunk failed after earlier ones went out: partial delivery.
  779. if last_error:
  780. logger.warning(
  781. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  782. len(message_ids), len(chunks), chat_id, last_error,
  783. )
  784. return SendResult(success=True, message_id=first_id, raw_response=last_resp)
  785. def format_message(self, content: str) -> str:
  786. """Normalise outgoing text for Chatto.
  787. Chatto renders Markdown natively, so there is nothing to escape or
  788. translate — the only transformations here are the ones that measurably
  789. render wrong: CRLF line endings (which show up as stray blank lines)
  790. and runs of more than two blank lines.
  791. BasePlatformAdapter override
  792. """
  793. if not content:
  794. return content
  795. normalised = content.replace("\r\n", "\n").replace("\r", "\n")
  796. while "\n\n\n\n" in normalised:
  797. normalised = normalised.replace("\n\n\n\n", "\n\n\n")
  798. return normalised
  799. async def edit_message(
  800. self,
  801. chat_id: str,
  802. message_id: str,
  803. content: str,
  804. *,
  805. finalize: bool = False,
  806. ) -> SendResult:
  807. """Edit a message we previously sent, via MessageService/UpdateMessage.
  808. The stream consumer drives streaming replies through this: without the
  809. override the base class reports "Not supported" and every incremental
  810. update arrives as a *new* message.
  811. ``finalize`` is a no-op for Chatto — an edit is an edit here, there is
  812. no in-progress card state to close out (hence no
  813. ``REQUIRES_EDIT_FINALIZE``).
  814. Content that exceeds the per-message limit is refused rather than
  815. silently truncated, so the caller falls back to ``send()``, which
  816. splits across messages.
  817. BasePlatformAdapter override
  818. """
  819. if not message_id:
  820. return SendResult(success=False, error="Chatto: no message id to edit")
  821. if not content:
  822. return SendResult(success=False, error="Empty message")
  823. formatted = self.format_message(content)
  824. if len(formatted) > ChattoConstants.MAX_MESSAGE_LENGTH:
  825. # Refuse instead of truncating: the caller's fallback path splits.
  826. return SendResult(
  827. success=False,
  828. error=(
  829. f"Chatto: edit exceeds {ChattoConstants.MAX_MESSAGE_LENGTH} "
  830. f"chars ({len(formatted)})"
  831. ),
  832. )
  833. try:
  834. client = await self._require_client()
  835. except RuntimeError:
  836. return SendResult(success=False, error="Chatto client not available", retryable=True)
  837. try:
  838. msg = await client.update_message(
  839. room_id=str(chat_id),
  840. event_id=str(message_id),
  841. body=formatted,
  842. )
  843. except ChattoError as e:
  844. logger.warning("Chatto: UpdateMessage failed for %s: %s", message_id, e)
  845. return SendResult(success=False, error=str(e), retryable=True)
  846. except Exception as e:
  847. logger.warning("Chatto: UpdateMessage error for %s: %s", message_id, e)
  848. return SendResult(success=False, error=str(e), retryable=False)
  849. # Our own edit comes back as a message_edited event; mark it seen so it
  850. # is never mistaken for inbound traffic.
  851. edited_id = getattr(msg, "id", "") or str(message_id)
  852. self._mark_seen(edited_id)
  853. return SendResult(success=True, message_id=edited_id, raw_response=msg)
  854. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  855. """Delete a message via MessageService/DeleteMessage.
  856. Used by the stream consumer's fresh-final cleanup (removing a preview
  857. message once the completed reply has been sent) and by the ephemeral
  858. reply TTL.
  859. BasePlatformAdapter override
  860. """
  861. if not chat_id or not message_id:
  862. return False
  863. try:
  864. client = await self._require_client()
  865. except RuntimeError:
  866. logger.warning("Chatto: DeleteMessage — client unavailable")
  867. return False
  868. try:
  869. return bool(await client.delete_message(
  870. room_id=str(chat_id), event_id=str(message_id),
  871. ))
  872. except ChattoError as e:
  873. logger.warning("Chatto: DeleteMessage failed for %s: %s", message_id, e)
  874. return False
  875. except Exception as e:
  876. logger.warning("Chatto: DeleteMessage error for %s: %s", message_id, e)
  877. return False
  878. async def create_handoff_thread(
  879. self, parent_chat_id: str, name: str,
  880. ) -> Optional[str]:
  881. """Anchor a session handoff in a fresh thread under *parent_chat_id*.
  882. Chatto threads hang off a message, not off the room, so we post a seed
  883. message and hand its ID back as the thread root — the same shape the
  884. Slack adapter uses. DMs don't support threads, so they get ``None``
  885. and the watcher keeps delivering into the DM itself.
  886. BasePlatformAdapter override
  887. """
  888. if not parent_chat_id:
  889. return None
  890. if self._room_kinds.get(parent_chat_id) == RoomKind.DM:
  891. logger.debug("Chatto: handoff thread skipped — %s is a DM", parent_chat_id)
  892. return None
  893. try:
  894. client = await self._require_client()
  895. except RuntimeError:
  896. logger.warning("Chatto: handoff thread — client unavailable")
  897. return None
  898. seed_text = f"🧵 Hermes handoff — **{(name or 'session').strip()[:80]}**"
  899. try:
  900. msg = await client.post_message(room_id=str(parent_chat_id), body=seed_text)
  901. except Exception as e:
  902. logger.warning(
  903. "Chatto: handoff thread seed-post failed for room %s: %s",
  904. parent_chat_id, e,
  905. )
  906. return None
  907. seed_id = getattr(msg, "id", "") or ""
  908. if not seed_id:
  909. logger.warning("Chatto: handoff thread seed-post returned no message id")
  910. return None
  911. self._mark_seen(seed_id)
  912. self._our_message_ids.add(seed_id)
  913. self._our_thread_roots.add(seed_id)
  914. try:
  915. await client.follow_thread(str(parent_chat_id), seed_id)
  916. except Exception:
  917. logger.debug(
  918. "Chatto: follow_thread failed for handoff %s/%s",
  919. parent_chat_id, seed_id, exc_info=True,
  920. )
  921. return seed_id
  922. # Overridden from BaseAdapter:
  923. async def send_typing(self, chat_id: str, metadata=None) -> None:
  924. """Start a persistent typing indicator for a room.
  925. Sends a typing ping every 10 seconds (Chatto's indicator likely
  926. lasts ~8-10s). The background loop runs until ``stop_typing()``
  927. is called or the task is cancelled.
  928. BasePlatformAdapter override
  929. """
  930. if chat_id in self._typing_tasks:
  931. return # already running
  932. async def _typing_loop() -> None:
  933. try:
  934. while True:
  935. try:
  936. try:
  937. client = await self._require_client()
  938. except RuntimeError:
  939. return
  940. await client.update_typing_indicator(room_id=str(chat_id))
  941. except asyncio.CancelledError:
  942. return
  943. except Exception:
  944. pass
  945. await asyncio.sleep(10)
  946. except asyncio.CancelledError:
  947. pass
  948. finally:
  949. self._typing_tasks.pop(chat_id, None)
  950. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  951. async def stop_typing(self, chat_id: str) -> None:
  952. """Stop the persistent typing indicator for a room.
  953. BasePlatformAdapter override
  954. """
  955. task = self._typing_tasks.pop(chat_id, None)
  956. if task:
  957. task.cancel()
  958. try:
  959. await task
  960. except (asyncio.CancelledError, Exception):
  961. pass
  962. async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
  963. """Get information about a chat/room.
  964. BasePlatformAdapter override
  965. """
  966. name = self._room_names.get(chat_id, chat_id)
  967. kind = self._room_kinds.get(chat_id)
  968. chat_type = "dm" if kind == RoomKind.DM else "group"
  969. return {
  970. "name": name,
  971. "type": chat_type,
  972. }
  973. # ------------------------------------------------------------------ #
  974. # Reactions
  975. # ------------------------------------------------------------------ #
  976. @staticmethod
  977. def _emoji_to_shortcode(emoji: str) -> str:
  978. """Convert a unicode emoji to a Chatto shortcode name.
  979. If the emoji is already a shortcode (no unicode mapping found),
  980. return it as-is.
  981. """
  982. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  983. if shortcode:
  984. return shortcode
  985. # Already a shortcode like "thumbsup" — return as-is
  986. return emoji
  987. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  988. """Add a reaction to a message via MessageService/AddReaction."""
  989. shortcode = self._emoji_to_shortcode(emoji)
  990. try:
  991. try:
  992. client = await self._require_client()
  993. except RuntimeError:
  994. logger.warning("Chatto: AddReaction — client unavailable")
  995. return False
  996. result = await client.add_reaction(
  997. room_id=room_id,
  998. message_event_id=message_id,
  999. emoji=shortcode,
  1000. )
  1001. return result
  1002. except ChattoError as e:
  1003. logger.warning("Chatto: AddReaction failed: %s", e)
  1004. return False
  1005. except Exception as e:
  1006. logger.warning("Chatto: AddReaction error: %s", e)
  1007. return False
  1008. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  1009. """Remove a reaction from a message via MessageService/RemoveReaction."""
  1010. shortcode = self._emoji_to_shortcode(emoji)
  1011. try:
  1012. try:
  1013. client = await self._require_client()
  1014. except RuntimeError:
  1015. logger.warning("Chatto: RemoveReaction — client unavailable")
  1016. return False
  1017. result = await client.remove_reaction(
  1018. room_id=str(chat_id),
  1019. message_event_id=str(message_id),
  1020. emoji=shortcode,
  1021. )
  1022. return result
  1023. except ChattoError as e:
  1024. logger.warning("Chatto: RemoveReaction failed: %s", e)
  1025. return False
  1026. except Exception as e:
  1027. logger.warning("Chatto: RemoveReaction error: %s", e)
  1028. return False
  1029. # ------------------------------------------------------------------ #
  1030. # DM initiation (Chatto-unique)
  1031. # ------------------------------------------------------------------ #
  1032. async def start_dm(self, user_id: str) -> Optional[str]:
  1033. """Start a direct message with a user via RoomService/StartDM.
  1034. Returns the room ID on success, or None on failure.
  1035. """
  1036. if not user_id:
  1037. return None
  1038. try:
  1039. try:
  1040. client = await self._require_client()
  1041. except RuntimeError:
  1042. return None
  1043. room = await client.start_dm(participant_ids=[str(user_id)])
  1044. self._room_names[room.id] = room.name
  1045. self._room_kinds[room.id] = room.kind
  1046. return room.id
  1047. except ChattoError as e:
  1048. logger.debug("Chatto: StartDM failed: %s", e)
  1049. return None
  1050. except Exception as e:
  1051. logger.debug("Chatto: StartDM error: %s", e)
  1052. return None
  1053. # ------------------------------------------------------------------ #
  1054. # Room creation (Chatto-unique)
  1055. # ------------------------------------------------------------------ #
  1056. async def create_room(
  1057. self,
  1058. name: str,
  1059. description: str = "",
  1060. group_id: str = "",
  1061. universal: bool = True,
  1062. ) -> Optional[str]:
  1063. """Create an ad-hoc room via RoomService/CreateRoom.
  1064. Returns the room ID on success, or None on failure.
  1065. """
  1066. try:
  1067. try:
  1068. client = await self._require_client()
  1069. except RuntimeError:
  1070. return None
  1071. room = await client.create_room(
  1072. name=name,
  1073. group_id=group_id or "",
  1074. description=description,
  1075. universal=universal,
  1076. )
  1077. rid = str(room.id) if room else ""
  1078. if rid:
  1079. self._room_names[rid] = room.name
  1080. self._room_kinds[rid] = room.kind
  1081. return rid
  1082. logger.debug("Chatto: CreateRoom returned no room id")
  1083. return None
  1084. except ChattoError as e:
  1085. logger.debug("Chatto: CreateRoom failed: %s", e)
  1086. return None
  1087. except Exception as e:
  1088. logger.debug("Chatto: CreateRoom error: %s", e)
  1089. return None
  1090. # ------------------------------------------------------------------ #
  1091. # Processing lifecycle hooks (reactions-based, like Discord)
  1092. # ------------------------------------------------------------------ #
  1093. def _event_room_and_message_id(self, event: MessageEvent) -> Tuple[str, str]:
  1094. """Extract room_id and message_id from a MessageEvent."""
  1095. message_id = event.message_id or ""
  1096. chat_id = event.source.chat_id
  1097. return chat_id, message_id
  1098. async def on_processing_start(self, event: MessageEvent) -> None:
  1099. """Add an 👀 (eyes) reaction to the incoming message.
  1100. BasePlatformAdapter override
  1101. """
  1102. logger.info("self.chatto_config.reactions.value: %s", self.chatto_config.reactions.value)
  1103. if not self.chatto_config.reactions.value:
  1104. return
  1105. chat_id, message_id = self._event_room_and_message_id(event)
  1106. if not chat_id or not message_id:
  1107. logger.warning("Chatto: on_processing_start — empty chat_id or message_id, skipping reaction")
  1108. return
  1109. await self.add_reaction(chat_id, message_id, "👀")
  1110. async def on_processing_complete(
  1111. self, event: MessageEvent, outcome: ProcessingOutcome
  1112. ) -> None:
  1113. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  1114. BasePlatformAdapter override
  1115. """
  1116. if not self.chatto_config.reactions.value:
  1117. return
  1118. chat_id, message_id = self._event_room_and_message_id(event)
  1119. if not chat_id or not message_id:
  1120. return
  1121. # Remove the processing eyes reaction
  1122. await self.remove_reaction(chat_id, message_id, "👀")
  1123. # Add the outcome reaction
  1124. if outcome == ProcessingOutcome.SUCCESS:
  1125. await self.add_reaction(chat_id, message_id, "✅")
  1126. elif outcome == ProcessingOutcome.FAILURE:
  1127. await self.add_reaction(chat_id, message_id, "❌")
  1128. # ------------------------------------------------------------------ #
  1129. # Asset upload (chunked)
  1130. # ------------------------------------------------------------------ #
  1131. async def _upload_asset(self, room_id: str, file_path: str) -> Optional[str]:
  1132. """Upload a file via the chunked AssetUploadService.
  1133. Returns the asset ID on success, or None on failure.
  1134. """
  1135. try:
  1136. with open(file_path, "rb") as f:
  1137. file_data = f.read()
  1138. except Exception as e:
  1139. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  1140. return None
  1141. if not file_data:
  1142. logger.error("Chatto: file %s is empty", file_path)
  1143. return None
  1144. file_size = len(file_data)
  1145. file_name = os.path.basename(file_path)
  1146. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  1147. sha256_hash = hashlib.sha256(file_data).hexdigest()
  1148. try:
  1149. try:
  1150. client = await self._require_client()
  1151. except RuntimeError:
  1152. logger.error("Chatto: upload aborted - no client available")
  1153. return None
  1154. # Step 1: Create upload session
  1155. upload = await client.create_upload(
  1156. room_id=room_id,
  1157. filename=file_name,
  1158. size=file_size,
  1159. sha256=sha256_hash,
  1160. content_type=mime_type,
  1161. )
  1162. upload_id = str(getattr(cast(Any, upload), "id", ""))
  1163. if not upload_id:
  1164. logger.error("Chatto: CreateUpload returned no upload ID")
  1165. return None
  1166. # Step 2: Upload chunks
  1167. offset = 0
  1168. while offset < file_size:
  1169. chunk = file_data[offset:offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  1170. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  1171. await client.upload_chunk(
  1172. upload_id=upload_id,
  1173. offset=offset,
  1174. content=chunk,
  1175. chunk_sha256=chunk_sha256,
  1176. )
  1177. offset += len(chunk)
  1178. # Step 3: Complete upload
  1179. upload, asset = await client.complete_upload(upload_id=upload_id)
  1180. if not asset:
  1181. logger.error("Chatto: CompleteUpload returned no asset")
  1182. return None
  1183. asset_id = str(getattr(cast(Any, asset), "id", ""))
  1184. logger.info("Chatto: uploaded %s as asset %s (%d bytes)", file_name, asset_id, file_size)
  1185. return asset_id
  1186. except ChattoError as e:
  1187. logger.error("Chatto: upload failed: %s", e)
  1188. return None
  1189. except Exception as e:
  1190. logger.error("Chatto: upload error: %s", e)
  1191. return None
  1192. async def _post_attachment_message(
  1193. self,
  1194. chat_id: str,
  1195. asset_ids: List[str],
  1196. caption: Optional[str],
  1197. reply_to: Optional[str],
  1198. metadata: Optional[Dict[str, Any]],
  1199. ) -> SendResult:
  1200. """Post one message carrying already-uploaded assets."""
  1201. thread_id = (metadata or {}).get("thread_id")
  1202. if reply_to:
  1203. thread_id = reply_to
  1204. try:
  1205. try:
  1206. client = await self._require_client()
  1207. except RuntimeError:
  1208. return SendResult(success=False, error="Chatto client not available", retryable=True)
  1209. msg = await client.post_message(
  1210. room_id=str(chat_id),
  1211. body=self.format_message(caption) if caption else "",
  1212. attachment_asset_ids=asset_ids,
  1213. thread_root_event_id=str(thread_id) if thread_id else "",
  1214. )
  1215. self._mark_seen(msg.id)
  1216. self._our_message_ids.add(msg.id)
  1217. return SendResult(success=True, message_id=msg.id, raw_response=msg)
  1218. except ChattoError as e:
  1219. return SendResult(success=False, error=str(e), retryable=True)
  1220. except Exception as e:
  1221. return SendResult(success=False, error=str(e), retryable=False)
  1222. async def _send_local_attachment(
  1223. self,
  1224. chat_id: str,
  1225. file_path: str,
  1226. caption: Optional[str],
  1227. reply_to: Optional[str],
  1228. metadata: Optional[Dict[str, Any]],
  1229. *,
  1230. kind: str,
  1231. ) -> SendResult:
  1232. """Upload a local file and post it as a native Chatto attachment.
  1233. Shared by ``send_image_file``/``send_document``/``send_video``/
  1234. ``send_voice`` — the upload mechanics are identical, only the wording of
  1235. the failure notice differs. On failure we send that notice as text and
  1236. never the host path (it leaks the Hermes home layout).
  1237. """
  1238. notice = f"⚠️ Couldn't deliver the {kind} attachment."
  1239. safe_path = self.validate_media_delivery_path(file_path)
  1240. if not safe_path:
  1241. logger.warning(
  1242. "[%s] send %s: unsafe path %s", self.name, kind, file_path,
  1243. )
  1244. text = f"{caption}\n{notice}" if caption else notice
  1245. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1246. asset_id = await self._upload_asset(str(chat_id), safe_path)
  1247. if not asset_id:
  1248. logger.warning(
  1249. "[%s] send %s: upload failed for %s", self.name, kind, safe_path,
  1250. )
  1251. text = f"{caption}\n{notice}" if caption else notice
  1252. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1253. return await self._post_attachment_message(
  1254. chat_id, [asset_id], caption, reply_to, metadata,
  1255. )
  1256. async def send_image_file(
  1257. self,
  1258. chat_id: str,
  1259. image_path: str,
  1260. caption: Optional[str] = None,
  1261. reply_to: Optional[str] = None,
  1262. metadata: Optional[Dict[str, Any]] = None,
  1263. **kwargs,
  1264. ) -> SendResult:
  1265. """Send a local image file via the chunked upload API.
  1266. The parameter is ``image_path``, not ``file_path``: every caller passes
  1267. it by keyword (``gateway/run.py:22354``, ``:22470``, and the base class's
  1268. own ``send_multiple_images`` file:// branch), so a renamed parameter
  1269. makes each of those raise TypeError and silently degrade to a text
  1270. notice.
  1271. BasePlatformAdapter override
  1272. """
  1273. return await self._send_local_attachment(
  1274. chat_id, image_path, caption, reply_to, metadata, kind="image",
  1275. )
  1276. async def send_document(
  1277. self,
  1278. chat_id: str,
  1279. file_path: str,
  1280. caption: Optional[str] = None,
  1281. file_name: Optional[str] = None,
  1282. reply_to: Optional[str] = None,
  1283. metadata: Optional[Dict[str, Any]] = None,
  1284. **kwargs,
  1285. ) -> SendResult:
  1286. """Send a local file as a native Chatto attachment.
  1287. ``file_name`` is the user-facing name the agent chose; Chatto takes the
  1288. filename from the upload session, so it only matters for the failure
  1289. notice.
  1290. BasePlatformAdapter override
  1291. """
  1292. result = await self._send_local_attachment(
  1293. chat_id, file_path, caption, reply_to, metadata, kind="file",
  1294. )
  1295. if not result.success and file_name:
  1296. logger.debug("Chatto: document delivery failed for %s", file_name)
  1297. return result
  1298. async def send_video(
  1299. self,
  1300. chat_id: str,
  1301. video_path: str,
  1302. caption: Optional[str] = None,
  1303. reply_to: Optional[str] = None,
  1304. metadata: Optional[Dict[str, Any]] = None,
  1305. **kwargs,
  1306. ) -> SendResult:
  1307. """Send a local video as a native Chatto attachment (Chatto transcodes
  1308. and plays it inline).
  1309. BasePlatformAdapter override
  1310. """
  1311. return await self._send_local_attachment(
  1312. chat_id, video_path, caption, reply_to, metadata, kind="video",
  1313. )
  1314. async def send_voice(
  1315. self,
  1316. chat_id: str,
  1317. audio_path: str,
  1318. caption: Optional[str] = None,
  1319. reply_to: Optional[str] = None,
  1320. metadata: Optional[Dict[str, Any]] = None,
  1321. **kwargs,
  1322. ) -> SendResult:
  1323. """Send a local audio file as a native Chatto attachment.
  1324. Chatto has no dedicated voice-bubble type, so this is an ordinary audio
  1325. attachment — still far better than the base class's text notice.
  1326. BasePlatformAdapter override
  1327. """
  1328. return await self._send_local_attachment(
  1329. chat_id, audio_path, caption, reply_to, metadata, kind="audio",
  1330. )
  1331. async def send_image(
  1332. self,
  1333. chat_id: str,
  1334. image_url: str,
  1335. caption: Optional[str] = None,
  1336. reply_to: Optional[str] = None,
  1337. metadata: Optional[Dict[str, Any]] = None,
  1338. ) -> SendResult:
  1339. """Send an image to a Chatto room.
  1340. Tries to download the image from the URL and upload it as a native
  1341. attachment. Falls back to sending the URL as a link (Chatto renders
  1342. link previews) if the download fails.
  1343. BasePlatformAdapter override
  1344. """
  1345. # Try downloading and uploading as attachment
  1346. try:
  1347. import tempfile
  1348. import urllib.request as _urllib_request
  1349. # Download to a temp file
  1350. parsed = urlsplit(image_url)
  1351. url_path = parsed.path
  1352. ext = os.path.splitext(url_path)[1] or ".png"
  1353. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1354. try:
  1355. os.close(tmp_fd)
  1356. req = _urllib_request.Request(image_url, headers={"User-Agent": "Hermes/1.0"})
  1357. try:
  1358. import ssl
  1359. ctx = ssl.create_default_context()
  1360. except Exception:
  1361. ctx = None
  1362. with _urllib_request.urlopen(req, timeout=ChattoConstants.HTTP_TIMEOUT, context=ctx) as resp:
  1363. with open(tmp_path, "wb") as f:
  1364. f.write(resp.read())
  1365. # Upload as attachment
  1366. result = await self.send_image_file(
  1367. chat_id, tmp_path, caption=caption,
  1368. reply_to=reply_to, metadata=metadata,
  1369. )
  1370. if result.success:
  1371. return result
  1372. finally:
  1373. try:
  1374. os.unlink(tmp_path)
  1375. except OSError:
  1376. pass
  1377. except Exception as e:
  1378. logger.debug("Chatto: send_image download/upload failed, falling back to link: %s", e)
  1379. # Fallback: send as link (Chatto renders link previews)
  1380. text = image_url
  1381. if caption:
  1382. text = f"{caption}\n{image_url}"
  1383. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1384. async def _materialise_image(self, image_url: str) -> Tuple[Optional[str], bool]:
  1385. """Resolve one ``send_multiple_images`` entry to a local file path.
  1386. Accepts ``http(s)://`` URLs (downloaded to a temp file), ``file://``
  1387. URIs and bare paths. Returns ``(path, is_temp)`` — the caller unlinks
  1388. when ``is_temp``. ``(None, False)`` means the entry is unusable.
  1389. """
  1390. import tempfile
  1391. from urllib.parse import unquote as _unquote
  1392. if image_url.startswith(("http://", "https://")):
  1393. parsed = urlsplit(image_url)
  1394. ext = os.path.splitext(parsed.path)[1] or ".png"
  1395. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1396. os.close(tmp_fd)
  1397. try:
  1398. data = await self._download_attachment_bytes(image_url)
  1399. with open(tmp_path, "wb") as f:
  1400. f.write(data)
  1401. except Exception as e:
  1402. logger.warning("Chatto: image download failed for %s: %s", image_url, e)
  1403. try:
  1404. os.unlink(tmp_path)
  1405. except OSError:
  1406. pass
  1407. return None, False
  1408. return tmp_path, True
  1409. local = image_url
  1410. if local.startswith("file://"):
  1411. local = _unquote(urlsplit(local).path)
  1412. return self.validate_media_delivery_path(local), False
  1413. async def send_multiple_images(
  1414. self,
  1415. chat_id: str,
  1416. images: List[Tuple[str, str]],
  1417. metadata: Optional[Dict[str, Any]] = None,
  1418. human_delay: float = 0.0,
  1419. ) -> None:
  1420. """Send a batch of images as ONE message with several attachments.
  1421. The base implementation posts each image separately; a Chatto message
  1422. carries a list of attachment assets, so a batch belongs in a single
  1423. message (and a single notification).
  1424. ``human_delay`` is ignored deliberately — there is only one outbound
  1425. call to pace. Entries that can't be fetched are dropped with a warning;
  1426. if nothing survives, we fall back to the base class so the user still
  1427. gets the links.
  1428. BasePlatformAdapter override
  1429. """
  1430. if len(images or []) < 2:
  1431. await super().send_multiple_images(
  1432. chat_id, images, metadata=metadata, human_delay=human_delay,
  1433. )
  1434. return
  1435. asset_ids: List[str] = []
  1436. captions: List[str] = []
  1437. for image_url, alt_text in images:
  1438. path, is_temp = await self._materialise_image(image_url)
  1439. if not path:
  1440. logger.warning("Chatto: skipping unusable image %s", image_url)
  1441. continue
  1442. try:
  1443. asset_id = await self._upload_asset(str(chat_id), path)
  1444. finally:
  1445. if is_temp:
  1446. try:
  1447. os.unlink(path)
  1448. except OSError:
  1449. pass
  1450. if not asset_id:
  1451. logger.warning("Chatto: upload failed for image %s", image_url)
  1452. continue
  1453. asset_ids.append(asset_id)
  1454. if alt_text:
  1455. captions.append(alt_text)
  1456. if not asset_ids:
  1457. logger.warning(
  1458. "Chatto: no image survived upload, falling back to per-image delivery",
  1459. )
  1460. await super().send_multiple_images(
  1461. chat_id, images, metadata=metadata, human_delay=human_delay,
  1462. )
  1463. return
  1464. if len(asset_ids) < len(images):
  1465. logger.warning(
  1466. "Chatto: sending %d of %d images — the rest could not be uploaded",
  1467. len(asset_ids), len(images),
  1468. )
  1469. await self._post_attachment_message(
  1470. chat_id, asset_ids, "\n".join(captions) or None, None, metadata,
  1471. )
  1472. # ---------------------------------------------------------------------------
  1473. # Cron / out-of-process delivery
  1474. # ---------------------------------------------------------------------------
  1475. async def hermes_standalone_sender_fn(
  1476. pconfig,
  1477. chat_id,
  1478. message,
  1479. *,
  1480. thread_id=None,
  1481. media_files=None,
  1482. force_document=False,
  1483. ) -> SendResult:
  1484. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  1485. Used by cron / scheduled routines that run out-of-process. Creates a
  1486. short-lived chattolib client, posts, and closes.
  1487. """
  1488. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  1489. # Create a temporary client for standalone sending — we need a base URL plus
  1490. # either a token or a full login/password pair.
  1491. has_credentials = bool(
  1492. chatto_config.token.value
  1493. or (chatto_config.login.value and chatto_config.password.value)
  1494. )
  1495. if not chatto_config.base_url.value or not has_credentials:
  1496. return SendResult(success=False, error="Chatto: base URL or credentials missing")
  1497. client: ChattoClient
  1498. try:
  1499. if chatto_config.token.value:
  1500. client = ChattoClient(base_url=chatto_config.base_url.value, token=chatto_config.token.value)
  1501. else:
  1502. client = await ChattoClient.login(
  1503. base_url=chatto_config.base_url.value,
  1504. login=chatto_config.login.value,
  1505. password=chatto_config.password.value,
  1506. )
  1507. except Exception as exc:
  1508. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  1509. try:
  1510. kwargs: Dict[str, Any] = {}
  1511. if chatto_config.auto_thread.value and thread_id:
  1512. kwargs["in_reply_to"] = thread_id
  1513. if media_files and media_files.get("attachment_asset_ids"):
  1514. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  1515. try:
  1516. posted = await client.post_message(chat_id, message, **kwargs)
  1517. except Exception as exc:
  1518. return SendResult(success=False, error=str(exc))
  1519. return SendResult(success=True, message_id=getattr(posted, "id", "") or None)
  1520. finally:
  1521. try:
  1522. await client.close()
  1523. except Exception as exc:
  1524. logger.error(
  1525. "Chatto standalone: error closing short-lived client (perhaps already closed): %s", exc,
  1526. )
  1527. def hermes_validate_config(config: PlatformConfig) -> bool:
  1528. """"
  1529. Function name should be the same as register argument name with "hermes_" prefix, so we
  1530. know that it is needed for plugin register(). Do not change signature.
  1531. - config
  1532. Check whether Chatto Plugin is configured. Compare to hermes_is_connected()."""
  1533. chatto_config = ChattoConfiguration(pconfig=config)
  1534. if len(chatto_config.allowed_users.value) > 0 and chatto_config.allow_all_users.value:
  1535. logger.info("Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both.")
  1536. return False
  1537. if chatto_config.base_url.value:
  1538. if (chatto_config.token.value is not None) or (chatto_config.login.value and chatto_config.password.value):
  1539. return True
  1540. else:
  1541. logger.error("Chatto: Minimally, either token or login/password must be set.")
  1542. else:
  1543. logger.error("Chatto: base_url must be set.")
  1544. return False
  1545. def hermes_check_fn() -> bool:
  1546. """Check if Chatto is configured and dependencies are available.
  1547. Add real logic?! Or just .. there are no dependencies.. always return true. Really. Docs suck."""
  1548. try:
  1549. import chattolib.client # noqa: F401 — vendored dependency probe
  1550. return True
  1551. except ImportError:
  1552. return False
  1553. # ---------------------------------------------------------------------------
  1554. # is_connected probe
  1555. # ---------------------------------------------------------------------------
  1556. def hermes_is_connected(config: PlatformConfig) -> bool:
  1557. """Check whether Chatto Plugin is connected. But where to? To the Hermes Agent? To Chatto Server?
  1558. The Hermes Agent plugin docs suck and it seems there are many functions to do the same."""
  1559. return bool(hermes_validate_config(config) and config.enabled)
  1560. def hermes_setup_fn() -> None:
  1561. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  1562. Function name should be the same as register argument name with "hermes_" prefix, so we
  1563. know that it is needed for plugin register().
  1564. """
  1565. from hermes_cli.setup import (
  1566. prompt,
  1567. prompt_yes_no,
  1568. save_env_value,
  1569. get_env_value,
  1570. print_header,
  1571. print_info,
  1572. print_warning,
  1573. print_success,
  1574. )
  1575. url = prompt(
  1576. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:")
  1577. if url:
  1578. save_env_value(ChattoConfiguration.base_url.env_name, url)
  1579. login = prompt("Chatto login (username):")
  1580. if login:
  1581. save_env_value(ChattoConfiguration.login.env_name, login)
  1582. password = prompt("Chatto password:", password=True)
  1583. if password:
  1584. save_env_value(ChattoConfiguration.password.env_name, password)
  1585. channels = prompt("Room IDs to watch (comma-separated, or empty for all):")
  1586. if channels:
  1587. save_env_value(ChattoConfiguration.channels_list.env_name, channels)
  1588. home = prompt("Home room ID for notifications (or empty):")
  1589. if home:
  1590. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  1591. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  1592. if allow_all:
  1593. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  1594. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  1595. def hermes_env_enablement_fn() -> Optional[dict]:
  1596. """Seed PlatformConfig.extra from env vars.
  1597. Returns a dict compatible with the PlatformConfig merge hook (or None
  1598. when no env-provided values are present).
  1599. Called by the platform registry during load_gateway_config().
  1600. Return None when the platform isn't minimally configured — the
  1601. caller then skips auto-enabling. Return a dict to seed extras.
  1602. The special 'home_channel' key is extracted and becomes a proper
  1603. HomeChannel dataclass on the PlatformConfig; every other key is
  1604. merged into PlatformConfig.extra.
  1605. Function name should be the same as register argument name with "hermes_" prefix, so we
  1606. know that it is needed for plugin register().
  1607. """
  1608. # Seed keys must be the config.yaml "extra" keys (config_key), NOT the env
  1609. # var names — ChattoConfiguration reads extra[config_key].
  1610. seed: Dict[str, Any] = {
  1611. ChattoConfiguration.base_url.config_key: (
  1612. os.getenv(ChattoConfiguration.base_url.env_name) or ChattoClient.DEFAULT_BASE_URL
  1613. ).strip(),
  1614. }
  1615. for field in ChattoConfiguration.fields():
  1616. if field.field_name == ChattoConfiguration.base_url.field_name:
  1617. continue
  1618. env_value = os.getenv(field.env_name)
  1619. if env_value:
  1620. seed[field.config_key] = env_value.strip()
  1621. logger.debug("seed: %s", {k: v for k, v in seed.items() if k not in ("token", "password")})
  1622. return seed
  1623. # ---------------------------------------------------------------------------
  1624. # Plugin registration entry point
  1625. # ---------------------------------------------------------------------------
  1626. def register(ctx) -> None:
  1627. """Plugin entry point — called by the Hermes plugin system."""
  1628. logger.info("Registering Chatto platform plugin on Hermes Agent")
  1629. logger.info("ChattoConfiguration.allowed_users.env_name: %s", ChattoConfiguration.allowed_users.env_name)
  1630. ctx.register_platform(
  1631. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  1632. label=ChattoConstants.PLATFORM_LABEL,
  1633. adapter_factory=hermes_adapter_factory,
  1634. check_fn=hermes_check_fn,
  1635. validate_config=hermes_validate_config,
  1636. is_connected=hermes_is_connected,
  1637. install_hint=ChattoConstants.INSTALL_HINT,
  1638. env_enablement_fn=hermes_env_enablement_fn,
  1639. setup_fn=hermes_setup_fn,
  1640. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  1641. standalone_sender_fn=hermes_standalone_sender_fn,
  1642. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  1643. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  1644. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  1645. emoji="💬",
  1646. allow_update_command=True,
  1647. pii_safe=False,
  1648. platform_hint=(
  1649. "You are chatting in Chatto (a self-hosted or cloud-hosted team or community chat server). "
  1650. "Markdown is supported. Users _may_ address you by @-mentioning your name. If configured, " \
  1651. "you also react without a @-mention. Direct messages reach you without a mention."
  1652. "Keep responses conversational."
  1653. ),
  1654. )