adapter.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  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) if hasattr(self, "format_message") else 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. # Overridden from BaseAdapter:
  786. async def send_typing(self, chat_id: str, metadata=None) -> None:
  787. """Start a persistent typing indicator for a room.
  788. Sends a typing ping every 10 seconds (Chatto's indicator likely
  789. lasts ~8-10s). The background loop runs until ``stop_typing()``
  790. is called or the task is cancelled.
  791. BasePlatformAdapter override
  792. """
  793. if chat_id in self._typing_tasks:
  794. return # already running
  795. async def _typing_loop() -> None:
  796. try:
  797. while True:
  798. try:
  799. try:
  800. client = await self._require_client()
  801. except RuntimeError:
  802. return
  803. await client.update_typing_indicator(room_id=str(chat_id))
  804. except asyncio.CancelledError:
  805. return
  806. except Exception:
  807. pass
  808. await asyncio.sleep(10)
  809. except asyncio.CancelledError:
  810. pass
  811. finally:
  812. self._typing_tasks.pop(chat_id, None)
  813. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  814. async def stop_typing(self, chat_id: str) -> None:
  815. """Stop the persistent typing indicator for a room.
  816. BasePlatformAdapter override
  817. """
  818. task = self._typing_tasks.pop(chat_id, None)
  819. if task:
  820. task.cancel()
  821. try:
  822. await task
  823. except (asyncio.CancelledError, Exception):
  824. pass
  825. async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
  826. """Get information about a chat/room.
  827. BasePlatformAdapter override
  828. """
  829. name = self._room_names.get(chat_id, chat_id)
  830. kind = self._room_kinds.get(chat_id)
  831. chat_type = "dm" if kind == RoomKind.DM else "group"
  832. return {
  833. "name": name,
  834. "type": chat_type,
  835. }
  836. # ------------------------------------------------------------------ #
  837. # Reactions
  838. # ------------------------------------------------------------------ #
  839. @staticmethod
  840. def _emoji_to_shortcode(emoji: str) -> str:
  841. """Convert a unicode emoji to a Chatto shortcode name.
  842. If the emoji is already a shortcode (no unicode mapping found),
  843. return it as-is.
  844. """
  845. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  846. if shortcode:
  847. return shortcode
  848. # Already a shortcode like "thumbsup" — return as-is
  849. return emoji
  850. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  851. """Add a reaction to a message via MessageService/AddReaction."""
  852. shortcode = self._emoji_to_shortcode(emoji)
  853. try:
  854. try:
  855. client = await self._require_client()
  856. except RuntimeError:
  857. logger.warning("Chatto: AddReaction — client unavailable")
  858. return False
  859. result = await client.add_reaction(
  860. room_id=room_id,
  861. message_event_id=message_id,
  862. emoji=shortcode,
  863. )
  864. return result
  865. except ChattoError as e:
  866. logger.warning("Chatto: AddReaction failed: %s", e)
  867. return False
  868. except Exception as e:
  869. logger.warning("Chatto: AddReaction error: %s", e)
  870. return False
  871. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  872. """Remove a reaction from a message via MessageService/RemoveReaction."""
  873. shortcode = self._emoji_to_shortcode(emoji)
  874. try:
  875. try:
  876. client = await self._require_client()
  877. except RuntimeError:
  878. logger.warning("Chatto: RemoveReaction — client unavailable")
  879. return False
  880. result = await client.remove_reaction(
  881. room_id=str(chat_id),
  882. message_event_id=str(message_id),
  883. emoji=shortcode,
  884. )
  885. return result
  886. except ChattoError as e:
  887. logger.warning("Chatto: RemoveReaction failed: %s", e)
  888. return False
  889. except Exception as e:
  890. logger.warning("Chatto: RemoveReaction error: %s", e)
  891. return False
  892. # ------------------------------------------------------------------ #
  893. # DM initiation (Chatto-unique)
  894. # ------------------------------------------------------------------ #
  895. async def start_dm(self, user_id: str) -> Optional[str]:
  896. """Start a direct message with a user via RoomService/StartDM.
  897. Returns the room ID on success, or None on failure.
  898. """
  899. if not user_id:
  900. return None
  901. try:
  902. try:
  903. client = await self._require_client()
  904. except RuntimeError:
  905. return None
  906. room = await client.start_dm(participant_ids=[str(user_id)])
  907. self._room_names[room.id] = room.name
  908. self._room_kinds[room.id] = room.kind
  909. return room.id
  910. except ChattoError as e:
  911. logger.debug("Chatto: StartDM failed: %s", e)
  912. return None
  913. except Exception as e:
  914. logger.debug("Chatto: StartDM error: %s", e)
  915. return None
  916. # ------------------------------------------------------------------ #
  917. # Room creation (Chatto-unique)
  918. # ------------------------------------------------------------------ #
  919. async def create_room(
  920. self,
  921. name: str,
  922. description: str = "",
  923. group_id: str = "",
  924. universal: bool = True,
  925. ) -> Optional[str]:
  926. """Create an ad-hoc room via RoomService/CreateRoom.
  927. Returns the room ID on success, or None on failure.
  928. """
  929. try:
  930. try:
  931. client = await self._require_client()
  932. except RuntimeError:
  933. return None
  934. room = await client.create_room(
  935. name=name,
  936. group_id=group_id or "",
  937. description=description,
  938. universal=universal,
  939. )
  940. rid = str(room.id) if room else ""
  941. if rid:
  942. self._room_names[rid] = room.name
  943. self._room_kinds[rid] = room.kind
  944. return rid
  945. logger.debug("Chatto: CreateRoom returned no room id")
  946. return None
  947. except ChattoError as e:
  948. logger.debug("Chatto: CreateRoom failed: %s", e)
  949. return None
  950. except Exception as e:
  951. logger.debug("Chatto: CreateRoom error: %s", e)
  952. return None
  953. # ------------------------------------------------------------------ #
  954. # Processing lifecycle hooks (reactions-based, like Discord)
  955. # ------------------------------------------------------------------ #
  956. def _event_room_and_message_id(self, event: MessageEvent) -> Tuple[str, str]:
  957. """Extract room_id and message_id from a MessageEvent."""
  958. message_id = event.message_id or ""
  959. chat_id = event.source.chat_id
  960. return chat_id, message_id
  961. async def on_processing_start(self, event: MessageEvent) -> None:
  962. """Add an 👀 (eyes) reaction to the incoming message.
  963. BasePlatformAdapter override
  964. """
  965. logger.info("self.chatto_config.reactions.value: %s", self.chatto_config.reactions.value)
  966. if not self.chatto_config.reactions.value:
  967. return
  968. chat_id, message_id = self._event_room_and_message_id(event)
  969. if not chat_id or not message_id:
  970. logger.warning("Chatto: on_processing_start — empty chat_id or message_id, skipping reaction")
  971. return
  972. await self.add_reaction(chat_id, message_id, "👀")
  973. async def on_processing_complete(
  974. self, event: MessageEvent, outcome: ProcessingOutcome
  975. ) -> None:
  976. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  977. BasePlatformAdapter override
  978. """
  979. if not self.chatto_config.reactions.value:
  980. return
  981. chat_id, message_id = self._event_room_and_message_id(event)
  982. if not chat_id or not message_id:
  983. return
  984. # Remove the processing eyes reaction
  985. await self.remove_reaction(chat_id, message_id, "👀")
  986. # Add the outcome reaction
  987. if outcome == ProcessingOutcome.SUCCESS:
  988. await self.add_reaction(chat_id, message_id, "✅")
  989. elif outcome == ProcessingOutcome.FAILURE:
  990. await self.add_reaction(chat_id, message_id, "❌")
  991. # ------------------------------------------------------------------ #
  992. # Asset upload (chunked)
  993. # ------------------------------------------------------------------ #
  994. async def _upload_asset(self, room_id: str, file_path: str) -> Optional[str]:
  995. """Upload a file via the chunked AssetUploadService.
  996. Returns the asset ID on success, or None on failure.
  997. """
  998. try:
  999. with open(file_path, "rb") as f:
  1000. file_data = f.read()
  1001. except Exception as e:
  1002. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  1003. return None
  1004. if not file_data:
  1005. logger.error("Chatto: file %s is empty", file_path)
  1006. return None
  1007. file_size = len(file_data)
  1008. file_name = os.path.basename(file_path)
  1009. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  1010. sha256_hash = hashlib.sha256(file_data).hexdigest()
  1011. try:
  1012. try:
  1013. client = await self._require_client()
  1014. except RuntimeError:
  1015. logger.error("Chatto: upload aborted - no client available")
  1016. return None
  1017. # Step 1: Create upload session
  1018. upload = await client.create_upload(
  1019. room_id=room_id,
  1020. filename=file_name,
  1021. size=file_size,
  1022. sha256=sha256_hash,
  1023. content_type=mime_type,
  1024. )
  1025. upload_id = str(getattr(cast(Any, upload), "id", ""))
  1026. if not upload_id:
  1027. logger.error("Chatto: CreateUpload returned no upload ID")
  1028. return None
  1029. # Step 2: Upload chunks
  1030. offset = 0
  1031. while offset < file_size:
  1032. chunk = file_data[offset:offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  1033. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  1034. await client.upload_chunk(
  1035. upload_id=upload_id,
  1036. offset=offset,
  1037. content=chunk,
  1038. chunk_sha256=chunk_sha256,
  1039. )
  1040. offset += len(chunk)
  1041. # Step 3: Complete upload
  1042. upload, asset = await client.complete_upload(upload_id=upload_id)
  1043. if not asset:
  1044. logger.error("Chatto: CompleteUpload returned no asset")
  1045. return None
  1046. asset_id = str(getattr(cast(Any, asset), "id", ""))
  1047. logger.info("Chatto: uploaded %s as asset %s (%d bytes)", file_name, asset_id, file_size)
  1048. return asset_id
  1049. except ChattoError as e:
  1050. logger.error("Chatto: upload failed: %s", e)
  1051. return None
  1052. except Exception as e:
  1053. logger.error("Chatto: upload error: %s", e)
  1054. return None
  1055. async def send_image_file(
  1056. self,
  1057. chat_id: str,
  1058. file_path: str,
  1059. caption: Optional[str] = None,
  1060. reply_to: Optional[str] = None,
  1061. metadata: Optional[Dict[str, Any]] = None,
  1062. ) -> SendResult:
  1063. """Send a local image file via the chunked upload API. Do not change signature.
  1064. BasePlatformAdapter override
  1065. """
  1066. # Validate the path is safe
  1067. safe_path = self.validate_media_delivery_path(file_path)
  1068. if not safe_path:
  1069. logger.warning("Chatto: send_image_file — unsafe path %s", file_path)
  1070. text = "⚠️ Couldn't deliver the image attachment."
  1071. if caption:
  1072. text = f"{caption}\n{text}"
  1073. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1074. asset_id = await self._upload_asset(str(chat_id), safe_path)
  1075. if not asset_id:
  1076. # Fallback to a notice
  1077. text = "⚠️ Couldn't deliver the image attachment."
  1078. if caption:
  1079. text = f"{caption}\n{text}"
  1080. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1081. thread_id = (metadata or {}).get("thread_id")
  1082. if reply_to:
  1083. thread_id = reply_to
  1084. try:
  1085. try:
  1086. client = await self._require_client()
  1087. except RuntimeError:
  1088. return SendResult(success=False, error="Chatto client not available", retryable=True)
  1089. msg = await client.post_message(
  1090. room_id=str(chat_id),
  1091. body=caption or "",
  1092. attachment_asset_ids=[asset_id],
  1093. thread_root_event_id=str(thread_id) if thread_id else "",
  1094. )
  1095. self._mark_seen(msg.id)
  1096. return SendResult(success=True, message_id=msg.id, raw_response=msg)
  1097. except ChattoError as e:
  1098. return SendResult(success=False, error=str(e), retryable=True)
  1099. except Exception as e:
  1100. return SendResult(success=False, error=str(e), retryable=False)
  1101. async def send_image(
  1102. self,
  1103. chat_id: str,
  1104. image_url: str,
  1105. caption: Optional[str] = None,
  1106. reply_to: Optional[str] = None,
  1107. metadata: Optional[Dict[str, Any]] = None,
  1108. ) -> SendResult:
  1109. """Send an image to a Chatto room.
  1110. Tries to download the image from the URL and upload it as a native
  1111. attachment. Falls back to sending the URL as a link (Chatto renders
  1112. link previews) if the download fails.
  1113. BasePlatformAdapter override
  1114. """
  1115. # Try downloading and uploading as attachment
  1116. try:
  1117. import tempfile
  1118. import urllib.request as _urllib_request
  1119. # Download to a temp file
  1120. parsed = urlsplit(image_url)
  1121. url_path = parsed.path
  1122. ext = os.path.splitext(url_path)[1] or ".png"
  1123. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1124. try:
  1125. os.close(tmp_fd)
  1126. req = _urllib_request.Request(image_url, headers={"User-Agent": "Hermes/1.0"})
  1127. try:
  1128. import ssl
  1129. ctx = ssl.create_default_context()
  1130. except Exception:
  1131. ctx = None
  1132. with _urllib_request.urlopen(req, timeout=ChattoConstants.HTTP_TIMEOUT, context=ctx) as resp:
  1133. with open(tmp_path, "wb") as f:
  1134. f.write(resp.read())
  1135. # Upload as attachment
  1136. result = await self.send_image_file(
  1137. chat_id, tmp_path, caption=caption,
  1138. reply_to=reply_to, metadata=metadata,
  1139. )
  1140. if result.success:
  1141. return result
  1142. finally:
  1143. try:
  1144. os.unlink(tmp_path)
  1145. except OSError:
  1146. pass
  1147. except Exception as e:
  1148. logger.debug("Chatto: send_image download/upload failed, falling back to link: %s", e)
  1149. # Fallback: send as link (Chatto renders link previews)
  1150. text = image_url
  1151. if caption:
  1152. text = f"{caption}\n{image_url}"
  1153. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1154. # ---------------------------------------------------------------------------
  1155. # Cron / out-of-process delivery
  1156. # ---------------------------------------------------------------------------
  1157. async def hermes_standalone_sender_fn(
  1158. pconfig,
  1159. chat_id,
  1160. message,
  1161. *,
  1162. thread_id=None,
  1163. media_files=None,
  1164. force_document=False,
  1165. ) -> SendResult:
  1166. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  1167. Used by cron / scheduled routines that run out-of-process. Creates a
  1168. short-lived chattolib client, posts, and closes.
  1169. """
  1170. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  1171. # Create a temporary client for standalone sending — we need a base URL plus
  1172. # either a token or a full login/password pair.
  1173. has_credentials = bool(
  1174. chatto_config.token.value
  1175. or (chatto_config.login.value and chatto_config.password.value)
  1176. )
  1177. if not chatto_config.base_url.value or not has_credentials:
  1178. return SendResult(success=False, error="Chatto: base URL or credentials missing")
  1179. client: ChattoClient
  1180. try:
  1181. if chatto_config.token.value:
  1182. client = ChattoClient(base_url=chatto_config.base_url.value, token=chatto_config.token.value)
  1183. else:
  1184. client = await ChattoClient.login(
  1185. base_url=chatto_config.base_url.value,
  1186. login=chatto_config.login.value,
  1187. password=chatto_config.password.value,
  1188. )
  1189. except Exception as exc:
  1190. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  1191. try:
  1192. kwargs: Dict[str, Any] = {}
  1193. if chatto_config.auto_thread.value and thread_id:
  1194. kwargs["in_reply_to"] = thread_id
  1195. if media_files and media_files.get("attachment_asset_ids"):
  1196. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  1197. try:
  1198. posted = await client.post_message(chat_id, message, **kwargs)
  1199. except Exception as exc:
  1200. return SendResult(success=False, error=str(exc))
  1201. return SendResult(success=True, message_id=getattr(posted, "id", "") or None)
  1202. finally:
  1203. try:
  1204. await client.close()
  1205. except Exception as exc:
  1206. logger.error(
  1207. "Chatto standalone: error closing short-lived client (perhaps already closed): %s", exc,
  1208. )
  1209. def hermes_validate_config(config: PlatformConfig) -> bool:
  1210. """"
  1211. Function name should be the same as register argument name with "hermes_" prefix, so we
  1212. know that it is needed for plugin register(). Do not change signature.
  1213. - config
  1214. Check whether Chatto Plugin is configured. Compare to hermes_is_connected()."""
  1215. chatto_config = ChattoConfiguration(pconfig=config)
  1216. if len(chatto_config.allowed_users.value) > 0 and chatto_config.allow_all_users.value:
  1217. logger.info("Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both.")
  1218. return False
  1219. if chatto_config.base_url.value:
  1220. if (chatto_config.token.value is not None) or (chatto_config.login.value and chatto_config.password.value):
  1221. return True
  1222. else:
  1223. logger.error("Chatto: Minimally, either token or login/password must be set.")
  1224. else:
  1225. logger.error("Chatto: base_url must be set.")
  1226. return False
  1227. def hermes_check_fn() -> bool:
  1228. """Check if Chatto is configured and dependencies are available.
  1229. Add real logic?! Or just .. there are no dependencies.. always return true. Really. Docs suck."""
  1230. try:
  1231. import chattolib.client # noqa: F401 — vendored dependency probe
  1232. return True
  1233. except ImportError:
  1234. return False
  1235. # ---------------------------------------------------------------------------
  1236. # is_connected probe
  1237. # ---------------------------------------------------------------------------
  1238. def hermes_is_connected(config: PlatformConfig) -> bool:
  1239. """Check whether Chatto Plugin is connected. But where to? To the Hermes Agent? To Chatto Server?
  1240. The Hermes Agent plugin docs suck and it seems there are many functions to do the same."""
  1241. return bool(hermes_validate_config(config) and config.enabled)
  1242. def hermes_setup_fn() -> None:
  1243. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  1244. Function name should be the same as register argument name with "hermes_" prefix, so we
  1245. know that it is needed for plugin register().
  1246. """
  1247. from hermes_cli.setup import (
  1248. prompt,
  1249. prompt_yes_no,
  1250. save_env_value,
  1251. get_env_value,
  1252. print_header,
  1253. print_info,
  1254. print_warning,
  1255. print_success,
  1256. )
  1257. url = prompt(
  1258. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:")
  1259. if url:
  1260. save_env_value(ChattoConfiguration.base_url.env_name, url)
  1261. login = prompt("Chatto login (username):")
  1262. if login:
  1263. save_env_value(ChattoConfiguration.login.env_name, login)
  1264. password = prompt("Chatto password:", password=True)
  1265. if password:
  1266. save_env_value(ChattoConfiguration.password.env_name, password)
  1267. channels = prompt("Room IDs to watch (comma-separated, or empty for all):")
  1268. if channels:
  1269. save_env_value(ChattoConfiguration.channels_list.env_name, channels)
  1270. home = prompt("Home room ID for notifications (or empty):")
  1271. if home:
  1272. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  1273. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  1274. if allow_all:
  1275. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  1276. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  1277. def hermes_env_enablement_fn() -> Optional[dict]:
  1278. """Seed PlatformConfig.extra from env vars.
  1279. Returns a dict compatible with the PlatformConfig merge hook (or None
  1280. when no env-provided values are present).
  1281. Called by the platform registry during load_gateway_config().
  1282. Return None when the platform isn't minimally configured — the
  1283. caller then skips auto-enabling. Return a dict to seed extras.
  1284. The special 'home_channel' key is extracted and becomes a proper
  1285. HomeChannel dataclass on the PlatformConfig; every other key is
  1286. merged into PlatformConfig.extra.
  1287. Function name should be the same as register argument name with "hermes_" prefix, so we
  1288. know that it is needed for plugin register().
  1289. """
  1290. # Seed keys must be the config.yaml "extra" keys (config_key), NOT the env
  1291. # var names — ChattoConfiguration reads extra[config_key].
  1292. seed: Dict[str, Any] = {
  1293. ChattoConfiguration.base_url.config_key: (
  1294. os.getenv(ChattoConfiguration.base_url.env_name) or ChattoClient.DEFAULT_BASE_URL
  1295. ).strip(),
  1296. }
  1297. for field in ChattoConfiguration.fields():
  1298. if field.field_name == ChattoConfiguration.base_url.field_name:
  1299. continue
  1300. env_value = os.getenv(field.env_name)
  1301. if env_value:
  1302. seed[field.config_key] = env_value.strip()
  1303. logger.debug("seed: %s", {k: v for k, v in seed.items() if k not in ("token", "password")})
  1304. return seed
  1305. # ---------------------------------------------------------------------------
  1306. # Plugin registration entry point
  1307. # ---------------------------------------------------------------------------
  1308. def register(ctx) -> None:
  1309. """Plugin entry point — called by the Hermes plugin system."""
  1310. logger.info("Registering Chatto platform plugin on Hermes Agent")
  1311. logger.info("ChattoConfiguration.allowed_users.env_name: %s", ChattoConfiguration.allowed_users.env_name)
  1312. ctx.register_platform(
  1313. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  1314. label=ChattoConstants.PLATFORM_LABEL,
  1315. adapter_factory=hermes_adapter_factory,
  1316. check_fn=hermes_check_fn,
  1317. validate_config=hermes_validate_config,
  1318. is_connected=hermes_is_connected,
  1319. install_hint=ChattoConstants.INSTALL_HINT,
  1320. env_enablement_fn=hermes_env_enablement_fn,
  1321. setup_fn=hermes_setup_fn,
  1322. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  1323. standalone_sender_fn=hermes_standalone_sender_fn,
  1324. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  1325. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  1326. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  1327. emoji="💬",
  1328. allow_update_command=True,
  1329. pii_safe=False,
  1330. platform_hint=(
  1331. "You are chatting in Chatto (a self-hosted or cloud-hosted team or community chat server). "
  1332. "Markdown is supported. Users _may_ address you by @-mentioning your name. If configured, " \
  1333. "you also react without a @-mention. Direct messages reach you without a mention."
  1334. "Keep responses conversational."
  1335. ),
  1336. )