adapter.py 80 KB

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