adapter.py 78 KB

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