adapter.py 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603
  1. """Chatto Platform Adapter for Hermes Agent.
  2. A plugin-based gateway adapter that connects to a Chatto server
  3. (self-hosted team chat) and relays messages to/from the Hermes agent.
  4. The adapter uses the chattolib library for all Chatto API interactions,
  5. including both outbound messaging and realtime WebSocket connections.
  6. """
  7. from __future__ import annotations
  8. import random
  9. from gateway.platforms.helpers import MessageDeduplicator
  10. # Put the vendored dependencies for THIS platform on sys.path before importing
  11. # anything from chattolib. Imported relatively as part of the plugin package and
  12. # absolutely when this module is loaded standalone (e.g. by the tests).
  13. try:
  14. from .vendor_path import setup_vendor_path
  15. except ImportError: # pragma: no cover - depends on how the module is loaded
  16. from vendor_path import setup_vendor_path
  17. setup_vendor_path()
  18. import asyncio
  19. import hashlib
  20. import logging
  21. import mimetypes
  22. import os
  23. import ssl
  24. import urllib.request as _urllib_request
  25. from datetime import UTC, datetime
  26. from enum import StrEnum
  27. from typing import Any, cast
  28. from urllib.parse import urlsplit
  29. logger = logging.getLogger(__name__)
  30. from gateway.config import Platform, PlatformConfig
  31. from gateway.platforms.base import (
  32. BasePlatformAdapter,
  33. MessageEvent,
  34. MessageType,
  35. ProcessingOutcome,
  36. SendResult,
  37. cache_media_bytes,
  38. get_inbound_media_max_bytes,
  39. validate_inbound_media_size,
  40. )
  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. ChattoRealtimeCloseError,
  58. ChattoRealtimeError,
  59. RealtimeEvent,
  60. stream_events,
  61. )
  62. from chattolib.realtime_types import (
  63. MessagePostedPayload,
  64. ReactionPayload,
  65. )
  66. from chattolib.types import PresenceStatus, RoomKind, RoomWithViewerState, User
  67. except ImportError as e:
  68. # Fail loudly: continuing here only defers the failure to a confusing
  69. # NameError somewhere deep in the adapter.
  70. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  71. raise
  72. try:
  73. from .platform_config import (
  74. ChattoConfiguration,
  75. ChattoConstants,
  76. )
  77. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  78. from platform_config import (
  79. ChattoConfiguration,
  80. ChattoConstants,
  81. )
  82. # --------------------------------------------------------------------------- #
  83. # Chat types
  84. # --------------------------------------------------------------------------- #
  85. class HermesChatType(StrEnum):
  86. """The ``chat_type`` vocabulary the Hermes gateway understands.
  87. Declared in ``gateway/session.py:161`` as ``"dm", "group", "channel",
  88. "thread"`` and consumed as a bare string all over the gateway:
  89. ``SessionSource.description`` (session.py:239) and the PII-redacting
  90. description in ``build_session_context_prompt`` (session.py:537) both
  91. branch on these exact values and fall back to a nameless generic case for
  92. anything else, and ``build_session_key`` puts the value straight into the
  93. session key. Passing a chattolib ``RoomKind`` (``"ROOM_KIND_CHANNEL"``)
  94. therefore does not fail loudly — it just quietly degrades what the agent is
  95. told about where it is.
  96. A StrEnum so it stays a drop-in ``str`` at every one of those call sites.
  97. GROUP vs CHANNEL
  98. ----------------
  99. There is no strict contract between the two, and the adapters disagree in
  100. practice: Slack labels every non-DM conversation ``"group"`` (including real
  101. channels), Discord uses both, and Telegram reserves ``"channel"`` for actual
  102. broadcast channels. The intended reading is ``group`` = ordinary
  103. multi-participant chat, ``channel`` = broadcast surface.
  104. The distinction only changes behaviour in three places:
  105. 1. Authorization (``gateway/authz_mixin.py``) — the only security-relevant
  106. one. The group-scoped env allowlists apply to ``{"group", "forum"}``
  107. ONLY, never to ``"channel"``: ``{PLATFORM}_GROUP_ALLOWED_USERS`` /
  108. ``_GROUP_ALLOWED_CHATS`` (:616), the chat-id allowlist (:708) and the
  109. Telegram legacy shim (:724). The adapter-delegation paths in turn treat
  110. all three alike (:461, :649, :674, :694), where the value only picks
  111. ``group_allow_from`` over ``allow_from`` from ``config.extra``.
  112. For Chatto both choices are equivalent today: those group env maps hold
  113. Telegram and QQBot only (:535-541), and our own allowlist runs through
  114. ``CHATTO_ALLOWED_USERS``, which is chat_type-independent.
  115. 2. What the agent is told — ``SessionSource.description`` renders
  116. ``"group: Name"`` vs ``"channel: Name"`` (session.py:239-246), likewise
  117. the PII-redacted variant (session.py:537-544).
  118. 3. The session key, which embeds the literal (session.py:1192). Changing
  119. the value for a room re-buckets its existing sessions.
  120. Explicitly NOT affected: ``is_shared_multi_user_session`` (session.py:1063)
  121. only looks at ``"dm"`` and ``thread_id``, so sender prefixes, the multi-user
  122. prompt line and ``group_sessions_per_user`` treat group and channel
  123. identically.
  124. """
  125. DM = "dm"
  126. GROUP = "group"
  127. CHANNEL = "channel"
  128. # Emitted by adapters whose thread events are their own chat type (Slack,
  129. # Discord). We don't: a Chatto thread keeps its room's chat_type and is
  130. # identified by ``thread_id`` on the source instead. Listed for the record,
  131. # because build_session_key rewrites the slot to "thread" itself
  132. # (session.py:1190).
  133. THREAD = "thread"
  134. # Not declared in session.py:161 but real: Telegram forum topics travel as
  135. # "forum", and the authz group allowlists above accept it alongside "group".
  136. # Chatto has no equivalent, so we never emit it.
  137. # Chatto only distinguishes DMs from channels. UNSPECIFIED means the server
  138. # sent a kind this vendored chattolib doesn't know: map it to the generic
  139. # multi-user bucket rather than guessing "channel", and never to "dm" — that
  140. # value drives session isolation (is_shared_multi_user_session, session.py:1063)
  141. # and would silently turn a room into a private conversation.
  142. #
  143. # CHANNEL for RoomKind.CHANNEL is the descriptive choice and carries no
  144. # behavioural cost (see the GROUP vs CHANNEL note above). Switching to GROUP for
  145. # Slack parity would be this one line — plus the re-bucketing of existing
  146. # sessions that point 3 of that note describes.
  147. _ROOM_KIND_TO_CHAT_TYPE: dict[RoomKind, HermesChatType] = {
  148. RoomKind.DM: HermesChatType.DM,
  149. RoomKind.CHANNEL: HermesChatType.CHANNEL,
  150. RoomKind.UNSPECIFIED: HermesChatType.GROUP,
  151. }
  152. def chat_type_for_room_kind(kind: RoomKind | None) -> HermesChatType:
  153. """Map a chattolib RoomKind onto the gateway's chat_type vocabulary.
  154. An unknown or missing kind becomes ``GROUP`` — see ``_ROOM_KIND_TO_CHAT_TYPE``.
  155. """
  156. if kind is None:
  157. return HermesChatType.GROUP
  158. return _ROOM_KIND_TO_CHAT_TYPE.get(kind, HermesChatType.GROUP)
  159. # Blocking filesystem/network helpers. The adapter runs on the shared gateway
  160. # event loop, so file reads and HTTP downloads are pushed to a worker thread
  161. # via asyncio.to_thread — a slow disk or dead image URL must not stall every
  162. # platform's message processing.
  163. def _read_file_bytes(path: str) -> bytes:
  164. """Read a whole file synchronously (run via asyncio.to_thread)."""
  165. with open(path, "rb") as f:
  166. return f.read()
  167. def _write_file_bytes(path: str, data: bytes) -> None:
  168. """Write bytes to a file synchronously (run via asyncio.to_thread)."""
  169. with open(path, "wb") as f:
  170. f.write(data)
  171. def _download_to_file(url: str, path: str, timeout: float) -> None:
  172. """Download ``url`` to ``path`` synchronously (run via asyncio.to_thread)."""
  173. req = _urllib_request.Request(url, headers={"User-Agent": "Hermes/1.0"})
  174. try:
  175. ctx = ssl.create_default_context()
  176. except Exception:
  177. ctx = None
  178. with _urllib_request.urlopen(req, timeout=timeout, context=ctx) as resp:
  179. _write_file_bytes(path, resp.read())
  180. # --------------------------------------------------------------------------- #
  181. # Adapter
  182. # --------------------------------------------------------------------------- #
  183. def hermes_adapter_factory(config: PlatformConfig):
  184. """Construct a ChattoAdapter from a PlatformConfig."""
  185. return ChattoAdapter(config)
  186. class ChattoAdapter(BasePlatformAdapter):
  187. """Chatto platform adapter.
  188. Receives messages via WebSocket realtime, sends via ConnectRPC.
  189. """
  190. _SPLIT_THRESHOLD = 9900
  191. # Read by BasePlatformAdapter.max_message_length_for_chat(), which the
  192. # gateway and the stream consumer use to chunk outgoing messages. Without
  193. # it they fall back to 4096 and split Chatto messages far earlier than
  194. # necessary — send() itself already truncates at 10000.
  195. MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  196. splits_long_messages = True
  197. supports_code_blocks: bool = True
  198. supports_status_text: bool = True # client.update_custom_status
  199. def __init__(self, pconfig: PlatformConfig):
  200. """Signature needs to be compatible with BasePlatformAdapter.__init__."""
  201. super().__init__(
  202. config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME)
  203. )
  204. # "extra" has been pre-processed by Hermes-Framework to be a dict of extra config values insode PlatformConfig.
  205. # --- Configuration from our configuration data class with some logic ---
  206. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  207. # ------ State -------
  208. # SDK runtime handle (injected by Hermes); annotate for Pylance
  209. self.sdk: Any = getattr(self, "sdk", None)
  210. # Our own user, filled in by connect(). Events arriving before connect()
  211. # completes must not blow up on an undefined attribute.
  212. self.me: User | None = None
  213. # --- Runtime state ---
  214. self._user_id: str = ""
  215. self._user_display: str = ""
  216. self._room_names: dict[str, str] = {}
  217. self._room_kinds: dict[str, RoomKind] = {}
  218. self._our_thread_roots: set = set() # thread root event IDs we created
  219. self._our_message_ids: set = (
  220. set()
  221. ) # message IDs we sent (for thread root detection)
  222. self._seen: list[str] = [] # Plain RealtimeEvent-id list
  223. self._resume_cursor: str | None = None
  224. self._watch_room_ids: list[str] = []
  225. # One-shot guard for the unjoined-home-channel warning in _refresh_rooms.
  226. self._home_warning_logged = False
  227. self._ws_task: asyncio.Task | None = None
  228. self._presence_task: asyncio.Task | None = None
  229. self._ws_ready: asyncio.Event | None = None
  230. self._ws_active = False
  231. self._ws_ref = None # reference to open websocket for dynamic resubscribe
  232. # Persistent typing indicator loops per room
  233. self._typing_tasks: dict[str, asyncio.Task] = {}
  234. # Member directory cache: user_id -> user info dict
  235. self._user_cache: dict[str, User] = {}
  236. # Handle -> does a user hold it. Cached both ways; see _mentions_someone_else.
  237. self._known_handles: dict[str, bool] = {}
  238. # Chattolib client cache and lock for async access.
  239. self._chatto_client: ChattoClient | None = None
  240. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  241. # Dedup — chattolib may redeliver events across reconnects.
  242. self._dedup = MessageDeduplicator()
  243. # ------------------------------------------------------------------ #
  244. # Auth
  245. # ------------------------------------------------------------------ #
  246. async def _get_chatto_client(self: ChattoAdapter) -> ChattoClient | None:
  247. """Get or create a ChattoClient instance."""
  248. if self._chatto_client is not None:
  249. return self._chatto_client
  250. async with self._chatto_client_lock:
  251. if self._chatto_client is not None:
  252. return self._chatto_client
  253. try:
  254. assert (
  255. self.chatto_config.login.value
  256. ) # now we can assume, _login is available.
  257. client = await self._open_client(
  258. base_url=self.chatto_config.base_url.value,
  259. login=self.chatto_config.login.value,
  260. password=self.chatto_config.password.value,
  261. token=self.chatto_config.token.value,
  262. )
  263. self._chatto_client = client
  264. self._token = client.token
  265. logger.info(
  266. "Chatto: logged in as '%s' via chattolib",
  267. self.chatto_config.login.value,
  268. )
  269. return client
  270. except ChattoAuthError as e:
  271. logger.error("Chatto: authentication failed: %s", e)
  272. return None
  273. except (ChattoError, ValueError) as e:
  274. logger.error("Chatto: failed to create client: %s", e)
  275. return None
  276. async def _require_client(self) -> ChattoClient:
  277. """Return a ChattoClient or raise RuntimeError if unavailable.
  278. Use this helper when the caller expects a client to exist and
  279. wants a single canonical failure path. Methods that prefer a
  280. soft-fail can catch RuntimeError and return gracefully.
  281. """
  282. client = await self._get_chatto_client()
  283. if client is None:
  284. raise RuntimeError("Chatto client unavailable")
  285. return client
  286. async def _ensure_token(self) -> bool:
  287. """Ensure we have a logged-in Chatto client and token."""
  288. if self.chatto_config.token.value and isinstance(
  289. self._chatto_client, ChattoClient
  290. ):
  291. return True
  292. client = await self._get_chatto_client()
  293. return client is not None
  294. # ------------------------------------------------------------------ #
  295. # Connection
  296. # ------------------------------------------------------------------ #
  297. async def _open_client(
  298. self,
  299. *,
  300. base_url: str,
  301. login: str,
  302. password: str,
  303. token: str | None = None,
  304. ) -> ChattoClient:
  305. """Return a connected ``ChattoClient`` using token or login/password."""
  306. if token:
  307. return ChattoClient(token=token, base_url=base_url)
  308. return await ChattoClient.login(login, password, base_url=base_url)
  309. async def connect(self, *, is_reconnect: bool = False) -> bool:
  310. """Connect to Chatto and start the realtime event stream.
  311. BasePlatformAdapter override
  312. """
  313. logger.info("Chatto: connecting...")
  314. if not await self._ensure_token():
  315. return False
  316. try:
  317. client = await self._require_client()
  318. except RuntimeError:
  319. self._set_fatal_error(
  320. "connect_failed", "Chatto client not available", retryable=True
  321. )
  322. return False
  323. # Get our first own user info
  324. try:
  325. self.me = await client.me()
  326. except Exception as exc:
  327. logger.error("Chatto: failed to get user info: %s", exc)
  328. self._set_fatal_error(
  329. "chatto_auth_failed",
  330. f"Chatto auth failed: {exc}",
  331. retryable=False,
  332. )
  333. try:
  334. assert self._chatto_client
  335. await self._chatto_client.close()
  336. finally:
  337. self._chatto_client = None
  338. return False
  339. # Announce online presence so the bot appears online in the member list.
  340. # The server treats this as a TTL, so _presence_refresh_loop below has to
  341. # keep re-announcing it — a single call here lapses back to offline.
  342. await self._announce_online()
  343. self._closing = False
  344. # Start background realtime WS event stream loop.
  345. self._ws_ready = asyncio.Event()
  346. self._ws_task = asyncio.create_task(
  347. self._chattolib_event_loop(),
  348. name="chatto-event-stream",
  349. )
  350. self._presence_task = asyncio.create_task(
  351. self._presence_refresh_loop(),
  352. name="chatto-presence-refresh",
  353. )
  354. self._mark_connected()
  355. logger.info(
  356. "Chatto: connected and authentiated to %s using login:'%s' (display_name:'%s' id: '%s')",
  357. self.chatto_config.base_url.value,
  358. self.me.login,
  359. self.me.display_name,
  360. self.me.id,
  361. )
  362. return True
  363. async def _announce_online(self) -> bool:
  364. """Tell the server we are online. Returns whether the call got through.
  365. Logged at warning level on failure: a silently dropped presence call is
  366. indistinguishable from a bot that is simply not running.
  367. """
  368. try:
  369. client = await self._require_client()
  370. await client.update_presence(status=PresenceStatus.ONLINE)
  371. return True
  372. except Exception as exc:
  373. logger.warning(
  374. "Chatto: presence refresh failed, bot may appear offline: %s", exc
  375. )
  376. return False
  377. async def _presence_refresh_loop(self) -> None:
  378. """Re-announce ONLINE until disconnect, since presence expires server-side.
  379. Failures are not fatal — the next tick tries again, so a blip in the
  380. presence endpoint costs at most one interval of visible offline time.
  381. """
  382. while not self._closing:
  383. await self._sleep_interruptible(ChattoConstants.PRESENCE_REFRESH_INTERVAL)
  384. if self._closing:
  385. return
  386. await self._announce_online()
  387. async def disconnect(self) -> None:
  388. """Stop WebSocket, presence refresh, typing tasks, and clear state.
  389. BasePlatformAdapter override
  390. """
  391. # No explicit offline broadcast: chattolib rejects OFFLINE outright
  392. # ("stop refreshing to go offline"), so cancelling the refresh loop
  393. # below is what actually takes the bot offline.
  394. self._ws_active = False
  395. self._closing = True
  396. # Cancel all typing tasks
  397. for chat_id in list(self._typing_tasks.keys()):
  398. await self.stop_typing(chat_id)
  399. if self._ws_task and not self._ws_task.done():
  400. self._ws_task.cancel()
  401. try:
  402. await self._ws_task
  403. except (asyncio.CancelledError, Exception):
  404. logger.debug(
  405. "Chatto: websocket task ended during disconnect", exc_info=True
  406. )
  407. self._ws_task = None
  408. if self._presence_task and not self._presence_task.done():
  409. self._presence_task.cancel()
  410. try:
  411. await self._presence_task
  412. except (asyncio.CancelledError, Exception):
  413. logger.debug(
  414. "Chatto: presence task ended during disconnect", exc_info=True
  415. )
  416. self._presence_task = None
  417. if self._chatto_client:
  418. try:
  419. await self._chatto_client.close()
  420. except Exception:
  421. logger.exception("Chatto: error closing client")
  422. finally:
  423. self._chatto_client = None
  424. self._token = None
  425. logger.info("Chatto: disconnected")
  426. self._mark_disconnected()
  427. async def _seed_room(self, room_id: str) -> None:
  428. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  429. try:
  430. try:
  431. client = await self._require_client()
  432. timeline_page = await client.get_room_events(room_id)
  433. except RuntimeError:
  434. logger.debug(
  435. "Chatto: _seed_room aborted - no client available for %s", room_id
  436. )
  437. return
  438. for ev in timeline_page.events:
  439. if ev.id:
  440. self._mark_seen(ev.id)
  441. logger.debug(
  442. "Chatto: seeded room %s with %d events",
  443. room_id,
  444. len(timeline_page.events),
  445. )
  446. except Exception as e:
  447. logger.debug("Chatto: get room events failed for %s: %s", room_id, e)
  448. # ------------------------------------------------------------------ #
  449. # Realtime Event List
  450. # ------------------------------------------------------------------ #
  451. def _mark_seen(self, event_id: str) -> None:
  452. self._seen.append(event_id)
  453. while len(self._seen) > ChattoConstants.SEEN_CAP:
  454. self._seen.remove(self._seen[0]) # fastest removal of first item in a list.
  455. def _is_seen(self, event_id: str) -> bool:
  456. return event_id in self._seen
  457. # ------------------------------------------------------------------ #
  458. # WebSocket Realtime Transport
  459. # ------------------------------------------------------------------ #
  460. def _mentions_me(self, body: str) -> bool:
  461. """Whether the message addresses this bot.
  462. By login, by display name, or by a broadcast handle — ``@here`` speaks
  463. to everyone present and the bot is one of them, so naming a colleague
  464. alongside it does not take the bot out of the audience.
  465. """
  466. if not self.me:
  467. return False
  468. for handle in (self.me.login, self.me.display_name):
  469. if handle and f"@{handle}" in body:
  470. return True
  471. return any(
  472. handle.lower() in ChattoConstants.BROADCAST_MENTIONS
  473. for handle in ChattoConstants.MENTION_RE.findall(body)
  474. )
  475. async def _handle_belongs_to_a_user(self, handle: str) -> bool:
  476. """Whether ``handle`` is the login of a real Chatto user.
  477. The API carries no mention entities — ``mention_confirmation_token`` is
  478. reserved in the message descriptor — so an @-token is only a candidate
  479. until the directory confirms it. Results are cached both ways, since
  480. the same handles recur and a miss is as reusable as a hit.
  481. """
  482. known = self._known_handles.get(handle)
  483. if known is not None:
  484. return known
  485. try:
  486. client = await self._require_client()
  487. member = await client.get_user(login=handle)
  488. except Exception as exc:
  489. # Unresolved means "not confirmed", so the message goes through.
  490. logger.debug("Chatto: could not resolve handle @%s: %s", handle, exc)
  491. return False
  492. exists = member is not None and member.user is not None
  493. self._known_handles[handle] = exists
  494. return exists
  495. async def _mentions_someone_else(self, body: str) -> bool:
  496. """Whether the message @-mentions a person who is not this bot.
  497. Broadcast handles are not a person — they address everyone present,
  498. the bot included, so they do not count as someone else. A handle no
  499. user holds is not a mention at all: someone writing *about* mentioning
  500. ("per @-mention", "@nonexistent") is talking to us, and staying silent
  501. on a false positive is worse than answering one.
  502. """
  503. for handle in ChattoConstants.MENTION_RE.findall(body):
  504. if handle.lower() in ChattoConstants.BROADCAST_MENTIONS:
  505. continue
  506. if self.me and handle in (self.me.login, self.me.display_name):
  507. continue
  508. if await self._handle_belongs_to_a_user(handle):
  509. return True
  510. return False
  511. def _check_auth(self, user: User) -> bool:
  512. """We roll our own auth-systen on the against the chatto_config'ured allowed_users etc.
  513. because.. Hermes authz_mixin.py IS NOT SANE.
  514. """
  515. if self.chatto_config.allow_all_users.value:
  516. return True
  517. if user.login in self.chatto_config.allowed_users.value:
  518. return True
  519. if user.id in self.chatto_config.allowed_users.value:
  520. return True
  521. logger.info(
  522. "Chatto: rejecting message from unauthorized user '%s' (%s)",
  523. user.login,
  524. user.id,
  525. )
  526. return False
  527. # ------------------------------------------------------------------ #
  528. # Room management over DM (/join, /leave)
  529. # ------------------------------------------------------------------ #
  530. _DM_COMMANDS = ("/join", "/leave")
  531. async def _handle_dm_command(self, room_id: str, body: str) -> bool:
  532. """Run a ``/join`` or ``/leave`` admin command sent as a direct message.
  533. Returns True when ``body`` is one of the commands — whether it
  534. succeeded or not — so the caller keeps it out of the agent pipeline.
  535. Membership lives on the Chatto server: a joined room reappears in
  536. every future ``list_rooms()`` and therefore survives restarts.
  537. """
  538. verb, _, argument = body.strip().partition(" ")
  539. if verb.lower() not in self._DM_COMMANDS:
  540. return False
  541. try:
  542. client = await self._require_client()
  543. except RuntimeError:
  544. await self.send(chat_id=room_id, content="Chatto client is not connected.")
  545. return True
  546. argument = argument.strip()
  547. if not argument:
  548. await self.send(
  549. chat_id=room_id,
  550. content="Usage: /join <room-id or #name> | /leave <room-id or #name>",
  551. )
  552. return True
  553. error, target = await self._resolve_room_target(client, argument)
  554. if error or target is None:
  555. await self.send(chat_id=room_id, content=error or "Room lookup failed.")
  556. return True
  557. if verb.lower() == "/join":
  558. reply = await self._run_join(client, target)
  559. else:
  560. reply = await self._run_leave(client, target)
  561. await self.send(chat_id=room_id, content=reply)
  562. return True
  563. async def _resolve_room_target(
  564. self,
  565. client: ChattoClient,
  566. argument: str,
  567. ) -> tuple[str | None, RoomWithViewerState | None]:
  568. """Resolve a /join//leave argument to a room.
  569. ``#name`` is looked up case-insensitively in a fresh directory scan
  570. (which also refreshes our name/kind caches); anything else is treated
  571. as a room ID and verified via GetRoom. An ambiguous name comes back as
  572. an error naming the candidates, so the admin can retry with an ID.
  573. """
  574. if not argument.startswith("#"):
  575. state = await client.get_room(argument)
  576. if state is None or state.room is None:
  577. return f"No room with ID '{argument}'.", None
  578. return None, state
  579. wanted = argument[1:].strip().casefold()
  580. matches: list[RoomWithViewerState] = []
  581. for state in await client.list_rooms() or []:
  582. room_obj = state.room if state else None
  583. if room_obj and (room_obj.name or "").strip().casefold() == wanted:
  584. matches.append(state)
  585. self._room_names[room_obj.id] = room_obj.name
  586. self._room_kinds[room_obj.id] = room_obj.kind
  587. if not matches:
  588. return f"No room named '{argument}'.", None
  589. if len(matches) > 1:
  590. candidates = "\n".join(f"• {m.room.name} ({m.room.id})" for m in matches)
  591. return (
  592. f"Several rooms are named '{argument}' — pick one by ID:\n{candidates}"
  593. ), None
  594. return None, matches[0]
  595. async def _run_join(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  596. """Join a room via RoomService/JoinRoom and watch it immediately.
  597. An account that already holds membership (invited natively in Chatto)
  598. needs no JoinRoom call — it only gets seeded into the watch list.
  599. """
  600. room_obj = state.room
  601. label = f"'{room_obj.name}' ({room_obj.id})"
  602. joined_room = room_obj
  603. if not state.viewer_state.is_member:
  604. try:
  605. joined_room = await client.join_room(room_obj.id) or room_obj
  606. except ChattoError as exc:
  607. logger.warning("Chatto: /join failed for %s (%s)", room_obj.id, exc)
  608. return f"Could not join {label}: {exc}"
  609. self._room_names[joined_room.id] = joined_room.name
  610. self._room_kinds[joined_room.id] = joined_room.kind
  611. if joined_room.id not in self._watch_room_ids:
  612. await self._seed_room(joined_room.id)
  613. self._watch_room_ids.append(joined_room.id)
  614. if state.viewer_state.is_member:
  615. return f"Already a member of {label} — watching it."
  616. return f"Joined {label}."
  617. async def _run_leave(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  618. """Leave a room via RoomService/LeaveRoom and stop watching it.
  619. Two rooms are refused: a DM conversation cannot be left, and leaving
  620. the configured home channel would silently break cron/notification
  621. delivery, which posts there through the standalone sender.
  622. """
  623. room_obj = state.room
  624. label = f"'{room_obj.name}' ({room_obj.id})"
  625. if room_obj.kind == RoomKind.DM:
  626. return "Direct messages cannot be left."
  627. home_id = (self.chatto_config.home_channel.value or "").strip()
  628. if home_id == room_obj.id:
  629. return (
  630. f"{label} is the configured home channel "
  631. "(CHATTO_HOME_CHANNEL); leaving it would break cron and "
  632. "notification delivery. Point CHATTO_HOME_CHANNEL elsewhere first."
  633. )
  634. try:
  635. left = await client.leave_room(room_obj.id)
  636. except ChattoError as exc:
  637. logger.warning("Chatto: /leave failed for %s (%s)", room_obj.id, exc)
  638. return f"Could not leave {label}: {exc}"
  639. if not left:
  640. return f"Chatto refused to leave {label}."
  641. if room_obj.id in self._watch_room_ids:
  642. self._watch_room_ids.remove(room_obj.id)
  643. return f"Left {label}."
  644. # ------------------------------------------------------------------ #
  645. # Inbound attachments
  646. # ------------------------------------------------------------------ #
  647. async def _download_attachment_bytes(self, url: str) -> bytes:
  648. """Download an attachment, refusing to buffer more than the gateway cap.
  649. The Content-Length header is checked first so an oversized asset is
  650. rejected before a single chunk is read; the running total is re-checked
  651. as chunks arrive, because a missing or lying header must not smuggle an
  652. unbounded body past the cap.
  653. """
  654. import httpx
  655. max_bytes = get_inbound_media_max_bytes()
  656. chunks: list[bytes] = []
  657. total = 0
  658. async with (
  659. httpx.AsyncClient(
  660. timeout=ChattoConstants.HTTP_TIMEOUT,
  661. follow_redirects=True,
  662. ) as http,
  663. http.stream("GET", url) as resp,
  664. ):
  665. resp.raise_for_status()
  666. declared = resp.headers.get("content-length")
  667. if declared:
  668. try:
  669. declared_size = int(declared)
  670. except ValueError:
  671. logger.debug("Chatto: ignoring invalid Content-Length %r", declared)
  672. else:
  673. validate_inbound_media_size(
  674. declared_size,
  675. media_type="attachment",
  676. max_bytes=max_bytes,
  677. )
  678. async for chunk in resp.aiter_bytes():
  679. total += len(chunk)
  680. validate_inbound_media_size(
  681. total,
  682. media_type="attachment",
  683. max_bytes=max_bytes,
  684. )
  685. chunks.append(chunk)
  686. return b"".join(chunks)
  687. async def _cache_attachments(
  688. self,
  689. room_id: str,
  690. attachments: list[Any],
  691. ) -> tuple[list[str], list[str], list[str]]:
  692. """Download message attachments into the gateway media cache.
  693. Returns ``(media_urls, media_types, media_kinds)`` — the paths are
  694. agent-visible cache paths, exactly what ``cache_media_bytes`` yields for
  695. every other platform. A failing attachment is logged and skipped: the
  696. message itself still reaches the agent.
  697. """
  698. media_urls: list[str] = []
  699. media_types: list[str] = []
  700. media_kinds: list[str] = []
  701. for att in attachments or []:
  702. asset_url = getattr(att, "asset_url", None)
  703. url = getattr(asset_url, "url", "") if asset_url else ""
  704. filename = getattr(att, "filename", "") or ""
  705. content_type = getattr(att, "content_type", "") or ""
  706. if not url:
  707. # Videos are announced before transcoding finishes, so the
  708. # signed URL can legitimately be missing on arrival.
  709. logger.info(
  710. "Chatto: attachment '%s' has no asset URL yet, skipping",
  711. filename,
  712. )
  713. continue
  714. try:
  715. data = await self._download_attachment_bytes(url)
  716. cached = cache_media_bytes(
  717. data,
  718. filename=filename,
  719. mime_type=content_type,
  720. )
  721. except Exception as e:
  722. logger.warning(
  723. "Chatto: failed to cache attachment '%s' (%s): %s",
  724. filename,
  725. content_type,
  726. e,
  727. )
  728. continue
  729. if cached is None:
  730. logger.warning(
  731. "Chatto: attachment '%s' (%s) could not be cached, skipping",
  732. filename,
  733. content_type,
  734. )
  735. continue
  736. media_urls.append(cached.path)
  737. media_types.append(cached.media_type)
  738. media_kinds.append(cached.kind)
  739. return media_urls, media_types, media_kinds
  740. @staticmethod
  741. def _message_type_for_media_kinds(media_kinds: list[str]) -> MessageType:
  742. """Pick the MessageType for a set of cached attachment kinds."""
  743. if "document" in media_kinds:
  744. return MessageType.DOCUMENT
  745. if "image" in media_kinds:
  746. return MessageType.PHOTO
  747. if "video" in media_kinds:
  748. return MessageType.VIDEO
  749. if "audio" in media_kinds:
  750. return MessageType.AUDIO
  751. return MessageType.TEXT
  752. async def _dispatch_message_posted(self, payload: MessagePostedPayload) -> None:
  753. try:
  754. client = await self._require_client()
  755. except RuntimeError:
  756. logger.warning("Chatto: chattolib event loop aborted - no client available")
  757. return
  758. logger.info("Chatto WS: 'message_posted' payload:%s", payload)
  759. message = await payload.fetch_message(client=client)
  760. if message is None or message.deleted_at:
  761. return
  762. message_body = message.body or ""
  763. logger.info("message: %s", message)
  764. attachments = list(message.attachments or [])
  765. # A message carrying only an image/PDF has an empty body — dropping it
  766. # here is what made attachments sent to Hermes disappear silently.
  767. if not message_body and not attachments:
  768. return
  769. if message.actor_id in self._user_cache:
  770. # try the user cache.
  771. user = self._user_cache.get(message.actor_id)
  772. else:
  773. # get the user and update cache.
  774. directory_member = await client.get_user(user_id=message.actor_id)
  775. if directory_member is None:
  776. return
  777. user = directory_member.user
  778. if user is None:
  779. return
  780. self._user_cache[user.id] = user
  781. if user is None:
  782. return
  783. if not self._check_auth(user):
  784. return
  785. # Todo: use a function that either reads from cache or gets room kind again.
  786. if self._room_kinds.get(message.room_id) is None:
  787. room_viewer_state = await client.get_room(message.room_id)
  788. if room_viewer_state is None:
  789. return
  790. if room_viewer_state.room is None:
  791. return
  792. self._room_kinds[message.room_id] = (
  793. room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  794. )
  795. room_kind = self._room_kinds.get(message.room_id)
  796. logger.info("message_body: %s room_kind: %s", message_body, room_kind)
  797. # Membership commands ride in over DMs only: they change what the bot
  798. # listens to and must never reach the agent pipeline or the mention
  799. # gates.
  800. if room_kind == RoomKind.DM and await self._handle_dm_command(
  801. message.room_id,
  802. message_body,
  803. ):
  804. return
  805. # require_mention deliberately gates channels only: in a channel the bot
  806. # is one of many listeners and must be addressed, whereas a DM is already
  807. # addressed at it — so DMs are always answered, mention or not.
  808. mentioned = False
  809. if (
  810. room_kind == RoomKind.CHANNEL
  811. and self.chatto_config.require_mention.value
  812. and self.me
  813. ):
  814. if self.me.login and not mentioned:
  815. mentioned = bool(f"@{self.me.login}" in message_body)
  816. if self.me.display_name and not mentioned:
  817. mentioned = bool(f"@{self.me.display_name}" in message_body)
  818. if mentioned is False:
  819. logger.debug(
  820. "Discarding message. Bot was not mentionend but require_mention is '%s'.",
  821. self.chatto_config.require_mention.value,
  822. )
  823. return
  824. logger.info("mentioned: %s", mentioned)
  825. # With require_mention off we see every message in the channel, including
  826. # ones plainly aimed at a named colleague. Answering those would be
  827. # barging in, so acknowledge that we read it and stay quiet. Checked
  828. # after the bot-mention test above, so a message naming us *and* someone
  829. # else still counts as ours.
  830. if (
  831. room_kind == RoomKind.CHANNEL
  832. and not self.chatto_config.require_mention.value
  833. and not self._mentions_me(message_body)
  834. and await self._mentions_someone_else(message_body)
  835. ):
  836. logger.info("Chatto: message addresses someone else, acknowledging only")
  837. if self.chatto_config.reactions.value:
  838. await self.add_reaction(message.room_id, message.id, "🫥")
  839. return
  840. # Thread anchoring — if the incoming message is inside a Chatto thread, we
  841. # keep that thread by default; otherwise leave thread_id unset so
  842. # replies land at the root.
  843. thread_id = (
  844. payload.thread_root_event_id or None
  845. ) # we could also take "payload.room_id" but then, we're in a thread already.
  846. if not thread_id and room_kind != RoomKind.DM:
  847. thread_id = message.id
  848. source = self.build_source(
  849. chat_id=payload.room_id,
  850. chat_name=self._room_names.get(message.room_id),
  851. chat_type=chat_type_for_room_kind(room_kind),
  852. user_id=message.actor_id,
  853. user_name=user.login, # use login, because display_name is changeable by anyone.
  854. thread_id=thread_id,
  855. message_id=payload.message_event_id,
  856. role_authorized=True,
  857. )
  858. # prepare a MessageEvent
  859. message_event = MessageEvent(
  860. text=message_body,
  861. source=source,
  862. message_id=message.id,
  863. timestamp=message.created_at or datetime.now(UTC),
  864. raw_message=message,
  865. reply_to_message_id=message.in_reply_to,
  866. )
  867. if message_event.is_command():
  868. message_event.message_type = MessageType.COMMAND
  869. # Attachments — download and hand the local cache paths to the gateway,
  870. # which runs vision enrichment / document extraction off media_urls.
  871. (
  872. message_event.media_urls,
  873. message_event.media_types,
  874. media_kinds,
  875. ) = await self._cache_attachments(
  876. payload.room_id,
  877. attachments,
  878. )
  879. if media_kinds:
  880. # Same precedence as the Teams/Signal adapters: document-context
  881. # injection gates strictly on DOCUMENT, image handling keys off the
  882. # per-path image/* MIME regardless of message_type.
  883. message_event.message_type = self._message_type_for_media_kinds(media_kinds)
  884. else:
  885. message_event.message_type = MessageType.TEXT
  886. logger.info("Chatto: Dispatching MessageEvent to Hermes: %s", message_event)
  887. await self.handle_message(message_event)
  888. return
  889. async def _forward_reaction(
  890. self,
  891. event: RealtimeEvent,
  892. payload: ReactionPayload,
  893. *,
  894. removed: bool,
  895. ) -> None:
  896. """Forward a human reaction to the gateway's reaction hook surface.
  897. The handler is registered by the gateway via ``set_reaction_handler``
  898. and fans out as ``reaction:added`` / ``reaction:removed`` through the
  899. HookRegistry. The dict shape mirrors the Slack adapter's — hook
  900. consumers are written against that contract, not against a per-platform
  901. one. Our own lifecycle reactions (👀/✅/❌) are dropped: forwarding them
  902. would feed the agent its own markers.
  903. """
  904. actor_id = event.actor_id
  905. if actor_id and self.me and actor_id == self.me.id:
  906. return
  907. if not payload.room_id or not payload.message_event_id or not actor_id:
  908. return
  909. handler = getattr(self, "_reaction_handler", None)
  910. if handler is None:
  911. return
  912. action = "removed" if removed else "added"
  913. try:
  914. await handler(
  915. {
  916. "platform": ChattoConstants.PLATFORM_NAME,
  917. "event_name": f"reaction:{action}",
  918. "reaction": payload.emoji,
  919. "user_id": actor_id,
  920. "item_user_id": None,
  921. "item_type": "message",
  922. "channel_id": payload.room_id,
  923. "message_ts": payload.message_event_id,
  924. "event_ts": event.id,
  925. "raw_event": event,
  926. },
  927. )
  928. except Exception: # pragma: no cover - the hook contract is non-blocking
  929. logger.debug("Chatto: reaction hook forwarding failed", exc_info=True)
  930. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  931. if self._is_seen(event.id):
  932. return
  933. if event.actor_id is None:
  934. return
  935. logger.info("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  936. if (event_payload := event.get("message_posted")) is not None:
  937. # Self-event filter — the actor_id on the envelope is authoritative
  938. # (chattolib does NOT filter this itself; see chatto-bridge notes).
  939. actor_id = event.actor_id
  940. if actor_id and self.me and actor_id == self.me.id:
  941. return
  942. await self._dispatch_message_posted(event_payload)
  943. elif event.kind in ("reaction_added", "reaction_removed"):
  944. reaction_payload = event.get(event.kind)
  945. if reaction_payload is not None:
  946. await self._forward_reaction(
  947. event,
  948. cast(ReactionPayload, reaction_payload),
  949. removed=event.kind == "reaction_removed",
  950. )
  951. # confirmed:
  952. elif event.kind in (
  953. "mention_notification",
  954. "projection_event",
  955. "presence_changed",
  956. "notification_dismissed",
  957. "room_marked_as_read",
  958. "user_typing",
  959. "notification_created",
  960. "new_direct_message_notification",
  961. "message_edited",
  962. "message_retracted",
  963. ):
  964. logger.debug(
  965. "Chatto: '%s' event received. Not yet implemented or not needed.",
  966. event.kind,
  967. )
  968. else:
  969. logger.error("Chatto: unknown event kind: '%s'", event.kind)
  970. async def _chattolib_event_loop(self) -> None:
  971. """Event loop using chattolib's stream_events.
  972. This replaces the manual WebSocket loop with chattolib's high-level
  973. stream_events() which provides pre-decoded RealtimeEvent objects.
  974. """
  975. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  976. while not self._closing:
  977. try:
  978. client = await self._require_client()
  979. await self._refresh_rooms()
  980. logger.info(
  981. "Chatto: starting chattolib event stream with %d rooms",
  982. len(self._watch_room_ids),
  983. )
  984. async for event in stream_events(client):
  985. if self._closing:
  986. return
  987. await self._handle_realtime_event(event)
  988. # Iterator exited cleanly — treat as a normal close and reconnect
  989. # with the local backoff (no server hint available).
  990. logger.info("Chatto: realtime stream ended, reconnecting")
  991. except asyncio.CancelledError:
  992. return
  993. except ChattoRealtimeCloseError as exc:
  994. if not exc.reconnect:
  995. logger.error(
  996. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  997. exc.code,
  998. exc.message,
  999. )
  1000. return
  1001. wait = max(
  1002. exc.retry_after_ms / 1000.0,
  1003. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF,
  1004. )
  1005. logger.warning(
  1006. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  1007. exc.code,
  1008. wait,
  1009. )
  1010. delay = (
  1011. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  1012. ) # server hint supersedes local backoff
  1013. await self._sleep_interruptible(wait)
  1014. continue
  1015. except ChattoRealtimeError as exc:
  1016. if getattr(exc, "fatal", False):
  1017. logger.error(
  1018. "Chatto: fatal realtime error (%s): %s", exc.code, exc.message
  1019. )
  1020. return
  1021. logger.warning(
  1022. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  1023. exc.code,
  1024. exc.message,
  1025. delay,
  1026. )
  1027. except Exception as exc:
  1028. logger.warning(
  1029. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  1030. exc,
  1031. delay,
  1032. )
  1033. if self._closing:
  1034. return
  1035. jitter = delay * 0.2 * random.random()
  1036. await self._sleep_interruptible(delay + jitter)
  1037. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  1038. async def _sleep_interruptible(self, seconds: float) -> None:
  1039. """Sleep in short slices so disconnect() cancels promptly."""
  1040. end = asyncio.get_running_loop().time() + seconds
  1041. while not self._closing:
  1042. remaining = end - asyncio.get_running_loop().time()
  1043. if remaining <= 0:
  1044. return
  1045. await asyncio.sleep(min(remaining, 0.5))
  1046. def _warn_if_home_channel_unjoined(self, member_ids: set[str]) -> None:
  1047. """Warn once when CHATTO_HOME_CHANNEL names a room the bot is not in.
  1048. Standalone cron delivery posts straight into that room with a fresh
  1049. client and no join logic of its own — without server-side membership
  1050. every proactive send fails there.
  1051. """
  1052. home_id = (self.chatto_config.home_channel.value or "").strip()
  1053. if (
  1054. not home_id
  1055. or home_id in member_ids
  1056. or home_id in self._watch_room_ids
  1057. or self._home_warning_logged
  1058. ):
  1059. return
  1060. self._home_warning_logged = True
  1061. logger.warning(
  1062. "Chatto: CHATTO_HOME_CHANNEL '%s' is not a joined room - cron and "
  1063. "notification delivery will fail until the bot joins it (invite "
  1064. "the account natively in Chatto, or DM it '/join').",
  1065. home_id,
  1066. )
  1067. async def _refresh_rooms(self) -> None:
  1068. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms."""
  1069. try:
  1070. client = await self._require_client()
  1071. except RuntimeError:
  1072. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  1073. return
  1074. try:
  1075. rooms_list = await client.list_rooms()
  1076. member_ids: set[str] = set()
  1077. new_room_ids: list[str] = []
  1078. for room_with_state in rooms_list:
  1079. if not room_with_state:
  1080. continue
  1081. room_obj = room_with_state.room or None
  1082. if not room_obj:
  1083. continue
  1084. self._room_names[room_obj.id] = room_obj.name
  1085. self._room_kinds[room_obj.id] = room_obj.kind
  1086. if not room_with_state.viewer_state.is_member:
  1087. continue
  1088. member_ids.add(room_obj.id)
  1089. if room_obj.id not in self._watch_room_ids:
  1090. new_room_ids.append(room_obj.id)
  1091. # Watched rooms we no longer belong to (left via /leave, kicked,
  1092. # deleted) drop out here — otherwise the next refresh would
  1093. # quietly re-add what /leave just removed.
  1094. stale_room_ids = [
  1095. rid for rid in self._watch_room_ids if rid not in member_ids
  1096. ]
  1097. for rid in stale_room_ids:
  1098. self._watch_room_ids.remove(rid)
  1099. if stale_room_ids:
  1100. logger.info(
  1101. "Chatto WS: no longer a member of %d room(s): %s",
  1102. len(stale_room_ids),
  1103. stale_room_ids,
  1104. )
  1105. self._warn_if_home_channel_unjoined(member_ids)
  1106. if not new_room_ids:
  1107. return
  1108. logger.info(
  1109. "Chatto WS: discovered %d new room(s): %s",
  1110. len(new_room_ids),
  1111. new_room_ids,
  1112. )
  1113. for rid in new_room_ids:
  1114. if self._room_kinds.get(rid) != RoomKind.DM:
  1115. await client.join_room(
  1116. rid
  1117. ) # but list_rooms() would not return any if we were not already joined?!
  1118. await self._seed_room(rid)
  1119. self._watch_room_ids.append(rid)
  1120. watch_room_names: list[str] = []
  1121. for rid in self._watch_room_ids:
  1122. watch_room_names.append(self._room_names[rid] + " (" + rid + ")")
  1123. logger.info(
  1124. "Chatto WS: Watching %d room(s): %s",
  1125. len(self._watch_room_ids),
  1126. ", ".join(watch_room_names),
  1127. )
  1128. except Exception:
  1129. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  1130. # ------------------------------------------------------------------ #
  1131. # Read state & notification dismissal (best-effort, Chatto-unique)
  1132. # ------------------------------------------------------------------ #
  1133. # Best-effort: mark all watched rooms as read (room_id may be undefined here)
  1134. for _rid in list(self._watch_room_ids):
  1135. try:
  1136. await client.mark_room_as_read(room_id=_rid)
  1137. await client.dismiss_all_notifications()
  1138. except Exception:
  1139. logger.debug(
  1140. "Chatto: mark_room_as_read failed for %s", _rid, exc_info=True
  1141. )
  1142. # ------------------------------------------------------------------ #
  1143. # Sending (ConnectRPC — unchanged from polling version)
  1144. # ------------------------------------------------------------------ #
  1145. async def send(
  1146. self,
  1147. chat_id: str,
  1148. content: str,
  1149. reply_to: str | None = None,
  1150. metadata: dict[str, Any] | None = None,
  1151. ) -> SendResult:
  1152. """Send a message to a Chatto room.
  1153. Long messages are split into chunks via ``truncate_message`` and
  1154. each chunk is sent as a separate CreateMessage call. The first
  1155. chunk's message ID is returned as ``message_id``.
  1156. When ``auto_thread`` is enabled and the incoming message was a
  1157. regular room message (not already in a thread), the first chunk is
  1158. sent as a room message and its ID becomes the thread root. Subsequent
  1159. chunks are sent in that thread. This mirrors Discord's auto_thread
  1160. behavior.
  1161. BasePlatformAdapter override
  1162. """
  1163. if not content:
  1164. return SendResult(success=False, error="Empty message")
  1165. formatted = self.format_message(content)
  1166. chunks = self.truncate_message(formatted, ChattoConstants.MAX_MESSAGE_LENGTH)
  1167. # Thread support — resolve thread_id once
  1168. # DM rooms don't support threads, so skip threading for DMs
  1169. thread_id = (metadata or {}).get("thread_id")
  1170. # Only use reply_to as thread_id if auto_thread is enabled.
  1171. # When auto_thread=false, responses go directly in the room
  1172. # without threading under the incoming message.
  1173. # If we already have thread_id from metadata, keep it (it's the
  1174. # thread root); only use reply_to when we don't already have one.
  1175. if reply_to and self.chatto_config.auto_thread.value and not thread_id:
  1176. thread_id = reply_to
  1177. # Check if this is a DM room — DMs don't support threads
  1178. room_kind = self._room_kinds.get(chat_id)
  1179. is_dm = room_kind == RoomKind.DM
  1180. if is_dm:
  1181. thread_id = None
  1182. # Auto-thread: by default, Chatto creates a thread for replies to room
  1183. # messages (not DMs, not already in a thread). This keeps conversations
  1184. # organized in the room. Can be disabled via extra.auto_thread=false.
  1185. use_auto_thread = (
  1186. self.chatto_config.auto_thread.value and not thread_id and not is_dm
  1187. )
  1188. message_ids: list[str] = []
  1189. last_error: str | None = None
  1190. retryable = False
  1191. try:
  1192. client = await self._require_client()
  1193. except RuntimeError:
  1194. return SendResult(
  1195. success=False, error="Chatto client not available", retryable=True
  1196. )
  1197. for i, chunk in enumerate(chunks):
  1198. try:
  1199. msg_obj = await client.post_message(
  1200. room_id=chat_id,
  1201. body=chunk,
  1202. thread_root_event_id=str(thread_id) if thread_id else "",
  1203. )
  1204. except ChattoError as e:
  1205. last_error = str(e)
  1206. retryable = True
  1207. break
  1208. except Exception as e:
  1209. last_error = str(e)
  1210. retryable = True
  1211. break
  1212. self._mark_seen(msg_obj.id)
  1213. message_ids.append(msg_obj.id)
  1214. self._our_message_ids.add(msg_obj.id)
  1215. # If we sent a message WITHOUT a thread_id, this message could
  1216. # become a thread root if someone replies to it
  1217. if not thread_id:
  1218. self._our_thread_roots.add(msg_obj.id)
  1219. # Auto-thread: first chunk becomes the thread root,
  1220. # subsequent chunks go in the thread
  1221. if use_auto_thread and i == 0 and not thread_id:
  1222. thread_id = msg_obj.id
  1223. # Nothing got through at all — report the failure instead of a phantom success.
  1224. if not message_ids:
  1225. return SendResult(
  1226. success=False,
  1227. error=last_error or "Chatto: message could not be sent",
  1228. retryable=retryable,
  1229. )
  1230. first_id = message_ids[0]
  1231. # ------------------------------------------------------------------ #
  1232. # Thread following (best-effort, Chatto-unique)
  1233. # ------------------------------------------------------------------ #
  1234. if thread_id:
  1235. try:
  1236. await client.follow_thread(chat_id, thread_id)
  1237. except Exception:
  1238. logger.debug(
  1239. "Chatto: follow_thread failed for %s/%s",
  1240. chat_id,
  1241. thread_id,
  1242. exc_info=True,
  1243. )
  1244. # A later chunk failed after earlier ones went out: partial delivery.
  1245. if last_error:
  1246. logger.warning(
  1247. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  1248. len(message_ids),
  1249. len(chunks),
  1250. chat_id,
  1251. last_error,
  1252. )
  1253. # raw_response stays unset (dict-shaped per the SendResult contract):
  1254. # gateway consumers such as the cron scheduler call .get() on it, so a
  1255. # chattolib Message here would crash delivery bookkeeping *after* the
  1256. # send already succeeded — the job then falls back to the standalone
  1257. # path and the room sees the message twice.
  1258. return SendResult(success=True, message_id=first_id)
  1259. def format_message(self, content: str) -> str:
  1260. """Normalise outgoing text for Chatto.
  1261. Chatto renders Markdown natively, so there is nothing to escape or
  1262. translate — the only transformations here are the ones that measurably
  1263. render wrong: CRLF line endings (which show up as stray blank lines)
  1264. and runs of more than two blank lines.
  1265. BasePlatformAdapter override
  1266. """
  1267. if not content:
  1268. return content
  1269. normalised = content.replace("\r\n", "\n").replace("\r", "\n")
  1270. while "\n\n\n\n" in normalised:
  1271. normalised = normalised.replace("\n\n\n\n", "\n\n\n")
  1272. return normalised
  1273. async def edit_message(
  1274. self,
  1275. chat_id: str,
  1276. message_id: str,
  1277. content: str,
  1278. *,
  1279. finalize: bool = False,
  1280. ) -> SendResult:
  1281. """Edit a message we previously sent, via MessageService/UpdateMessage.
  1282. The stream consumer drives streaming replies through this: without the
  1283. override the base class reports "Not supported" and every incremental
  1284. update arrives as a *new* message.
  1285. ``finalize`` is a no-op for Chatto — an edit is an edit here, there is
  1286. no in-progress card state to close out (hence no
  1287. ``REQUIRES_EDIT_FINALIZE``).
  1288. Content that exceeds the per-message limit is refused rather than
  1289. silently truncated, so the caller falls back to ``send()``, which
  1290. splits across messages.
  1291. BasePlatformAdapter override
  1292. """
  1293. if not message_id:
  1294. return SendResult(success=False, error="Chatto: no message id to edit")
  1295. if not content:
  1296. return SendResult(success=False, error="Empty message")
  1297. formatted = self.format_message(content)
  1298. if len(formatted) > ChattoConstants.MAX_MESSAGE_LENGTH:
  1299. # Refuse instead of truncating: the caller's fallback path splits.
  1300. return SendResult(
  1301. success=False,
  1302. error=(
  1303. f"Chatto: edit exceeds {ChattoConstants.MAX_MESSAGE_LENGTH} "
  1304. f"chars ({len(formatted)})"
  1305. ),
  1306. )
  1307. try:
  1308. client = await self._require_client()
  1309. except RuntimeError:
  1310. return SendResult(
  1311. success=False, error="Chatto client not available", retryable=True
  1312. )
  1313. try:
  1314. msg = await client.update_message(
  1315. room_id=str(chat_id),
  1316. event_id=str(message_id),
  1317. body=formatted,
  1318. )
  1319. except ChattoError as e:
  1320. logger.warning("Chatto: UpdateMessage failed for %s: %s", message_id, e)
  1321. return SendResult(success=False, error=str(e), retryable=True)
  1322. except Exception as e:
  1323. logger.warning("Chatto: UpdateMessage error for %s: %s", message_id, e)
  1324. return SendResult(success=False, error=str(e), retryable=False)
  1325. # Our own edit comes back as a message_edited event; mark it seen so it
  1326. # is never mistaken for inbound traffic.
  1327. edited_id = getattr(msg, "id", "") or str(message_id)
  1328. self._mark_seen(edited_id)
  1329. return SendResult(success=True, message_id=edited_id)
  1330. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  1331. """Delete a message via MessageService/DeleteMessage.
  1332. Used by the stream consumer's fresh-final cleanup (removing a preview
  1333. message once the completed reply has been sent) and by the ephemeral
  1334. reply TTL.
  1335. BasePlatformAdapter override
  1336. """
  1337. if not chat_id or not message_id:
  1338. return False
  1339. try:
  1340. client = await self._require_client()
  1341. except RuntimeError:
  1342. logger.warning("Chatto: DeleteMessage — client unavailable")
  1343. return False
  1344. try:
  1345. return bool(
  1346. await client.delete_message(
  1347. room_id=str(chat_id),
  1348. event_id=str(message_id),
  1349. )
  1350. )
  1351. except ChattoError as e:
  1352. logger.warning("Chatto: DeleteMessage failed for %s: %s", message_id, e)
  1353. return False
  1354. except Exception as e:
  1355. logger.warning("Chatto: DeleteMessage error for %s: %s", message_id, e)
  1356. return False
  1357. async def create_handoff_thread(
  1358. self,
  1359. parent_chat_id: str,
  1360. name: str,
  1361. ) -> str | None:
  1362. """Anchor a session handoff in a fresh thread under *parent_chat_id*.
  1363. Chatto threads hang off a message, not off the room, so we post a seed
  1364. message and hand its ID back as the thread root — the same shape the
  1365. Slack adapter uses. DMs don't support threads, so they get ``None``
  1366. and the watcher keeps delivering into the DM itself.
  1367. BasePlatformAdapter override
  1368. """
  1369. if not parent_chat_id:
  1370. return None
  1371. if self._room_kinds.get(parent_chat_id) == RoomKind.DM:
  1372. logger.debug("Chatto: handoff thread skipped — %s is a DM", parent_chat_id)
  1373. return None
  1374. try:
  1375. client = await self._require_client()
  1376. except RuntimeError:
  1377. logger.warning("Chatto: handoff thread — client unavailable")
  1378. return None
  1379. seed_text = f"🧵 Hermes handoff — **{(name or 'session').strip()[:80]}**"
  1380. try:
  1381. msg = await client.post_message(room_id=str(parent_chat_id), body=seed_text)
  1382. except Exception as e:
  1383. logger.warning(
  1384. "Chatto: handoff thread seed-post failed for room %s: %s",
  1385. parent_chat_id,
  1386. e,
  1387. )
  1388. return None
  1389. seed_id = getattr(msg, "id", "") or ""
  1390. if not seed_id:
  1391. logger.warning("Chatto: handoff thread seed-post returned no message id")
  1392. return None
  1393. self._mark_seen(seed_id)
  1394. self._our_message_ids.add(seed_id)
  1395. self._our_thread_roots.add(seed_id)
  1396. try:
  1397. await client.follow_thread(str(parent_chat_id), seed_id)
  1398. except Exception:
  1399. logger.debug(
  1400. "Chatto: follow_thread failed for handoff %s/%s",
  1401. parent_chat_id,
  1402. seed_id,
  1403. exc_info=True,
  1404. )
  1405. return seed_id
  1406. # Overridden from BaseAdapter:
  1407. async def send_typing(self, chat_id: str, metadata=None) -> None:
  1408. """Start a persistent typing indicator for a room.
  1409. Sends a typing ping every 10 seconds (Chatto's indicator likely
  1410. lasts ~8-10s). The background loop runs until ``stop_typing()``
  1411. is called or the task is cancelled.
  1412. BasePlatformAdapter override
  1413. """
  1414. if chat_id in self._typing_tasks:
  1415. return # already running
  1416. async def _typing_loop() -> None:
  1417. try:
  1418. while True:
  1419. try:
  1420. try:
  1421. client = await self._require_client()
  1422. except RuntimeError:
  1423. return
  1424. await client.update_typing_indicator(room_id=str(chat_id))
  1425. except asyncio.CancelledError:
  1426. return
  1427. except Exception:
  1428. logger.debug(
  1429. "Chatto: typing indicator refresh failed for %s",
  1430. chat_id,
  1431. exc_info=True,
  1432. )
  1433. await asyncio.sleep(10)
  1434. except asyncio.CancelledError:
  1435. pass
  1436. finally:
  1437. self._typing_tasks.pop(chat_id, None)
  1438. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  1439. async def stop_typing(self, chat_id: str) -> None:
  1440. """Stop the persistent typing indicator for a room.
  1441. BasePlatformAdapter override
  1442. """
  1443. task = self._typing_tasks.pop(chat_id, None)
  1444. if task:
  1445. task.cancel()
  1446. try:
  1447. await task
  1448. except (asyncio.CancelledError, Exception):
  1449. logger.debug("Chatto: typing task ended for %s", chat_id, exc_info=True)
  1450. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  1451. """Get information about a chat/room.
  1452. BasePlatformAdapter override
  1453. """
  1454. name = self._room_names.get(chat_id, chat_id)
  1455. kind = self._room_kinds.get(chat_id)
  1456. return {
  1457. "name": name,
  1458. "type": chat_type_for_room_kind(kind).value,
  1459. }
  1460. # ------------------------------------------------------------------ #
  1461. # Reactions
  1462. # ------------------------------------------------------------------ #
  1463. @staticmethod
  1464. def _emoji_to_shortcode(emoji: str) -> str:
  1465. """Convert a unicode emoji to a Chatto shortcode name.
  1466. If the emoji is already a shortcode (no unicode mapping found),
  1467. return it as-is.
  1468. """
  1469. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  1470. if shortcode:
  1471. return shortcode
  1472. # Already a shortcode like "thumbsup" — return as-is
  1473. return emoji
  1474. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  1475. """Add a reaction to a message via MessageService/AddReaction."""
  1476. shortcode = self._emoji_to_shortcode(emoji)
  1477. try:
  1478. try:
  1479. client = await self._require_client()
  1480. except RuntimeError:
  1481. logger.warning("Chatto: AddReaction — client unavailable")
  1482. return False
  1483. result = await client.add_reaction(
  1484. room_id=room_id,
  1485. message_event_id=message_id,
  1486. emoji=shortcode,
  1487. )
  1488. return result
  1489. except ChattoError as e:
  1490. logger.warning("Chatto: AddReaction failed: %s", e)
  1491. return False
  1492. except Exception as e:
  1493. logger.warning("Chatto: AddReaction error: %s", e)
  1494. return False
  1495. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  1496. """Remove a reaction from a message via MessageService/RemoveReaction."""
  1497. shortcode = self._emoji_to_shortcode(emoji)
  1498. try:
  1499. try:
  1500. client = await self._require_client()
  1501. except RuntimeError:
  1502. logger.warning("Chatto: RemoveReaction — client unavailable")
  1503. return False
  1504. result = await client.remove_reaction(
  1505. room_id=str(chat_id),
  1506. message_event_id=str(message_id),
  1507. emoji=shortcode,
  1508. )
  1509. return result
  1510. except ChattoError as e:
  1511. logger.warning("Chatto: RemoveReaction failed: %s", e)
  1512. return False
  1513. except Exception as e:
  1514. logger.warning("Chatto: RemoveReaction error: %s", e)
  1515. return False
  1516. # ------------------------------------------------------------------ #
  1517. # DM initiation (Chatto-unique)
  1518. # ------------------------------------------------------------------ #
  1519. async def start_dm(self, user_id: str) -> str | None:
  1520. """Start a direct message with a user via RoomService/StartDM.
  1521. Returns the room ID on success, or None on failure.
  1522. """
  1523. if not user_id:
  1524. return None
  1525. try:
  1526. try:
  1527. client = await self._require_client()
  1528. except RuntimeError:
  1529. return None
  1530. room = await client.start_dm(participant_ids=[str(user_id)])
  1531. self._room_names[room.id] = room.name
  1532. self._room_kinds[room.id] = room.kind
  1533. return room.id
  1534. except ChattoError as e:
  1535. logger.debug("Chatto: StartDM failed: %s", e)
  1536. return None
  1537. except Exception as e:
  1538. logger.debug("Chatto: StartDM error: %s", e)
  1539. return None
  1540. # ------------------------------------------------------------------ #
  1541. # Room creation (Chatto-unique)
  1542. # ------------------------------------------------------------------ #
  1543. async def create_room(
  1544. self,
  1545. name: str,
  1546. description: str = "",
  1547. group_id: str = "",
  1548. universal: bool = True,
  1549. ) -> str | None:
  1550. """Create an ad-hoc room via RoomService/CreateRoom.
  1551. Returns the room ID on success, or None on failure.
  1552. """
  1553. try:
  1554. try:
  1555. client = await self._require_client()
  1556. except RuntimeError:
  1557. return None
  1558. room = await client.create_room(
  1559. name=name,
  1560. group_id=group_id or "",
  1561. description=description,
  1562. universal=universal,
  1563. )
  1564. rid = str(room.id) if room else ""
  1565. if rid:
  1566. self._room_names[rid] = room.name
  1567. self._room_kinds[rid] = room.kind
  1568. return rid
  1569. logger.debug("Chatto: CreateRoom returned no room id")
  1570. return None
  1571. except ChattoError as e:
  1572. logger.debug("Chatto: CreateRoom failed: %s", e)
  1573. return None
  1574. except Exception as e:
  1575. logger.debug("Chatto: CreateRoom error: %s", e)
  1576. return None
  1577. # ------------------------------------------------------------------ #
  1578. # Processing lifecycle hooks (reactions-based, like Discord)
  1579. # ------------------------------------------------------------------ #
  1580. def _event_room_and_message_id(self, event: MessageEvent) -> tuple[str, str]:
  1581. """Extract room_id and message_id from a MessageEvent."""
  1582. message_id = event.message_id or ""
  1583. chat_id = event.source.chat_id
  1584. return chat_id, message_id
  1585. async def on_processing_start(self, event: MessageEvent) -> None:
  1586. """Add an 👀 (eyes) reaction to the incoming message.
  1587. BasePlatformAdapter override
  1588. """
  1589. if not self.chatto_config.reactions.value:
  1590. return
  1591. chat_id, message_id = self._event_room_and_message_id(event)
  1592. if not chat_id or not message_id:
  1593. # Routine, not a fault: the gateway runs agent-initiated turns
  1594. # (heartbeat polls, goal continuations) through the same pipeline
  1595. # with message_id=None, and there is no inbound message to mark.
  1596. logger.debug(
  1597. "Chatto: nothing to react to (chat_id=%r, message_id=%r)",
  1598. chat_id,
  1599. message_id,
  1600. )
  1601. return
  1602. await self.add_reaction(chat_id, message_id, "👀")
  1603. async def on_processing_complete(
  1604. self,
  1605. event: MessageEvent,
  1606. outcome: ProcessingOutcome,
  1607. ) -> None:
  1608. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  1609. BasePlatformAdapter override
  1610. """
  1611. if not self.chatto_config.reactions.value:
  1612. return
  1613. chat_id, message_id = self._event_room_and_message_id(event)
  1614. if not chat_id or not message_id:
  1615. return
  1616. # Remove the processing eyes reaction
  1617. await self.remove_reaction(chat_id, message_id, "👀")
  1618. # Add the outcome reaction
  1619. if outcome == ProcessingOutcome.SUCCESS:
  1620. await self.add_reaction(chat_id, message_id, "✅")
  1621. elif outcome == ProcessingOutcome.FAILURE:
  1622. await self.add_reaction(chat_id, message_id, "❌")
  1623. elif outcome == ProcessingOutcome.CANCELLED:
  1624. await self.add_reaction(chat_id, message_id, "🚫")
  1625. # ------------------------------------------------------------------ #
  1626. # Asset upload (chunked)
  1627. # ------------------------------------------------------------------ #
  1628. async def _upload_asset(self, room_id: str, file_path: str) -> str | None:
  1629. """Upload a file via the chunked AssetUploadService.
  1630. Returns the asset ID on success, or None on failure.
  1631. """
  1632. try:
  1633. file_data = await asyncio.to_thread(_read_file_bytes, file_path)
  1634. except Exception as e:
  1635. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  1636. return None
  1637. if not file_data:
  1638. logger.error("Chatto: file %s is empty", file_path)
  1639. return None
  1640. file_size = len(file_data)
  1641. file_name = os.path.basename(file_path)
  1642. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  1643. sha256_hash = hashlib.sha256(file_data).hexdigest()
  1644. try:
  1645. try:
  1646. client = await self._require_client()
  1647. except RuntimeError:
  1648. logger.error("Chatto: upload aborted - no client available")
  1649. return None
  1650. # Step 1: Create upload session
  1651. upload = await client.create_upload(
  1652. room_id=room_id,
  1653. filename=file_name,
  1654. size=file_size,
  1655. sha256=sha256_hash,
  1656. content_type=mime_type,
  1657. )
  1658. # AssetUpload names this upload_id, not id — reading it through an
  1659. # untyped getattr default is what let the mismatch reach production.
  1660. upload_id = upload.upload_id
  1661. if not upload_id:
  1662. logger.error("Chatto: CreateUpload returned no upload ID")
  1663. return None
  1664. # Step 2: Upload chunks
  1665. offset = 0
  1666. while offset < file_size:
  1667. chunk = file_data[offset : offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  1668. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  1669. await client.upload_chunk(
  1670. upload_id=upload_id,
  1671. offset=offset,
  1672. content=chunk,
  1673. chunk_sha256=chunk_sha256,
  1674. )
  1675. offset += len(chunk)
  1676. # Step 3: Complete upload
  1677. upload, asset = await client.complete_upload(upload_id=upload_id)
  1678. if not asset:
  1679. logger.error("Chatto: CompleteUpload returned no asset")
  1680. return None
  1681. asset_id = str(getattr(cast(Any, asset), "id", ""))
  1682. logger.info(
  1683. "Chatto: uploaded %s as asset %s (%d bytes)",
  1684. file_name,
  1685. asset_id,
  1686. file_size,
  1687. )
  1688. return asset_id
  1689. except ChattoError as e:
  1690. logger.error("Chatto: upload failed: %s", e)
  1691. return None
  1692. except Exception as e:
  1693. logger.error("Chatto: upload error: %s", e)
  1694. return None
  1695. async def _post_attachment_message(
  1696. self,
  1697. chat_id: str,
  1698. asset_ids: list[str],
  1699. caption: str | None,
  1700. reply_to: str | None,
  1701. metadata: dict[str, Any] | None,
  1702. ) -> SendResult:
  1703. """Post one message carrying already-uploaded assets."""
  1704. thread_id = (metadata or {}).get("thread_id")
  1705. if reply_to:
  1706. thread_id = reply_to
  1707. try:
  1708. try:
  1709. client = await self._require_client()
  1710. except RuntimeError:
  1711. return SendResult(
  1712. success=False, error="Chatto client not available", retryable=True
  1713. )
  1714. msg = await client.post_message(
  1715. room_id=str(chat_id),
  1716. body=self.format_message(caption) if caption else "",
  1717. attachment_asset_ids=asset_ids,
  1718. thread_root_event_id=str(thread_id) if thread_id else "",
  1719. )
  1720. self._mark_seen(msg.id)
  1721. self._our_message_ids.add(msg.id)
  1722. return SendResult(success=True, message_id=msg.id)
  1723. except ChattoError as e:
  1724. return SendResult(success=False, error=str(e), retryable=True)
  1725. except Exception as e:
  1726. return SendResult(success=False, error=str(e), retryable=False)
  1727. async def _send_local_attachment(
  1728. self,
  1729. chat_id: str,
  1730. file_path: str,
  1731. caption: str | None,
  1732. reply_to: str | None,
  1733. metadata: dict[str, Any] | None,
  1734. *,
  1735. kind: str,
  1736. ) -> SendResult:
  1737. """Upload a local file and post it as a native Chatto attachment.
  1738. Shared by ``send_image_file``/``send_document``/``send_video``/
  1739. ``send_voice`` — the upload mechanics are identical, only the wording of
  1740. the failure notice differs. On failure we send that notice as text and
  1741. never the host path (it leaks the Hermes home layout).
  1742. """
  1743. notice = f"⚠️ Couldn't deliver the {kind} attachment."
  1744. safe_path = self.validate_media_delivery_path(file_path)
  1745. if not safe_path:
  1746. logger.warning(
  1747. "[%s] send %s: unsafe path %s",
  1748. self.name,
  1749. kind,
  1750. file_path,
  1751. )
  1752. text = f"{caption}\n{notice}" if caption else notice
  1753. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1754. asset_id = await self._upload_asset(str(chat_id), safe_path)
  1755. if not asset_id:
  1756. logger.warning(
  1757. "[%s] send %s: upload failed for %s",
  1758. self.name,
  1759. kind,
  1760. safe_path,
  1761. )
  1762. text = f"{caption}\n{notice}" if caption else notice
  1763. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1764. return await self._post_attachment_message(
  1765. chat_id,
  1766. [asset_id],
  1767. caption,
  1768. reply_to,
  1769. metadata,
  1770. )
  1771. async def send_image_file(
  1772. self,
  1773. chat_id: str,
  1774. image_path: str,
  1775. caption: str | None = None,
  1776. reply_to: str | None = None,
  1777. metadata: dict[str, Any] | None = None,
  1778. **kwargs,
  1779. ) -> SendResult:
  1780. """Send a local image file via the chunked upload API.
  1781. The parameter is ``image_path``, not ``file_path``: every caller passes
  1782. it by keyword (``gateway/run.py:22354``, ``:22470``, and the base class's
  1783. own ``send_multiple_images`` file:// branch), so a renamed parameter
  1784. makes each of those raise TypeError and silently degrade to a text
  1785. notice.
  1786. BasePlatformAdapter override
  1787. """
  1788. return await self._send_local_attachment(
  1789. chat_id,
  1790. image_path,
  1791. caption,
  1792. reply_to,
  1793. metadata,
  1794. kind="image",
  1795. )
  1796. async def send_document(
  1797. self,
  1798. chat_id: str,
  1799. file_path: str,
  1800. caption: str | None = None,
  1801. file_name: str | None = None,
  1802. reply_to: str | None = None,
  1803. metadata: dict[str, Any] | None = None,
  1804. **kwargs,
  1805. ) -> SendResult:
  1806. """Send a local file as a native Chatto attachment.
  1807. ``file_name`` is the user-facing name the agent chose; Chatto takes the
  1808. filename from the upload session, so it only matters for the failure
  1809. notice.
  1810. BasePlatformAdapter override
  1811. """
  1812. result = await self._send_local_attachment(
  1813. chat_id,
  1814. file_path,
  1815. caption,
  1816. reply_to,
  1817. metadata,
  1818. kind="file",
  1819. )
  1820. if not result.success and file_name:
  1821. logger.debug("Chatto: document delivery failed for %s", file_name)
  1822. return result
  1823. async def send_video(
  1824. self,
  1825. chat_id: str,
  1826. video_path: str,
  1827. caption: str | None = None,
  1828. reply_to: str | None = None,
  1829. metadata: dict[str, Any] | None = None,
  1830. **kwargs,
  1831. ) -> SendResult:
  1832. """Send a local video as a native Chatto attachment.
  1833. Chatto transcodes and plays it inline.
  1834. BasePlatformAdapter override
  1835. """
  1836. return await self._send_local_attachment(
  1837. chat_id,
  1838. video_path,
  1839. caption,
  1840. reply_to,
  1841. metadata,
  1842. kind="video",
  1843. )
  1844. async def send_voice(
  1845. self,
  1846. chat_id: str,
  1847. audio_path: str,
  1848. caption: str | None = None,
  1849. reply_to: str | None = None,
  1850. metadata: dict[str, Any] | None = None,
  1851. **kwargs,
  1852. ) -> SendResult:
  1853. """Send a local audio file as a native Chatto attachment.
  1854. Chatto has no dedicated voice-bubble type, so this is an ordinary audio
  1855. attachment — still far better than the base class's text notice.
  1856. BasePlatformAdapter override
  1857. """
  1858. return await self._send_local_attachment(
  1859. chat_id,
  1860. audio_path,
  1861. caption,
  1862. reply_to,
  1863. metadata,
  1864. kind="audio",
  1865. )
  1866. async def send_image(
  1867. self,
  1868. chat_id: str,
  1869. image_url: str,
  1870. caption: str | None = None,
  1871. reply_to: str | None = None,
  1872. metadata: dict[str, Any] | None = None,
  1873. ) -> SendResult:
  1874. """Send an image to a Chatto room.
  1875. Tries to download the image from the URL and upload it as a native
  1876. attachment. Falls back to sending the URL as a link (Chatto renders
  1877. link previews) if the download fails.
  1878. BasePlatformAdapter override
  1879. """
  1880. # Try downloading and uploading as attachment
  1881. try:
  1882. import tempfile
  1883. # Download to a temp file
  1884. parsed = urlsplit(image_url)
  1885. url_path = parsed.path
  1886. ext = os.path.splitext(url_path)[1] or ".png"
  1887. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1888. try:
  1889. os.close(tmp_fd)
  1890. await asyncio.to_thread(
  1891. _download_to_file,
  1892. image_url,
  1893. tmp_path,
  1894. ChattoConstants.HTTP_TIMEOUT,
  1895. )
  1896. # Upload as attachment
  1897. result = await self.send_image_file(
  1898. chat_id,
  1899. tmp_path,
  1900. caption=caption,
  1901. reply_to=reply_to,
  1902. metadata=metadata,
  1903. )
  1904. if result.success:
  1905. return result
  1906. finally:
  1907. try:
  1908. os.unlink(tmp_path)
  1909. except OSError:
  1910. pass
  1911. except Exception as e:
  1912. logger.debug(
  1913. "Chatto: send_image download/upload failed, falling back to link: %s", e
  1914. )
  1915. # Fallback: send as link (Chatto renders link previews)
  1916. text = image_url
  1917. if caption:
  1918. text = f"{caption}\n{image_url}"
  1919. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1920. async def _materialise_image(self, image_url: str) -> tuple[str | None, bool]:
  1921. """Resolve one ``send_multiple_images`` entry to a local file path.
  1922. Accepts ``http(s)://`` URLs (downloaded to a temp file), ``file://``
  1923. URIs and bare paths. Returns ``(path, is_temp)`` — the caller unlinks
  1924. when ``is_temp``. ``(None, False)`` means the entry is unusable.
  1925. """
  1926. import tempfile
  1927. from urllib.parse import unquote as _unquote
  1928. if image_url.startswith(("http://", "https://")):
  1929. parsed = urlsplit(image_url)
  1930. ext = os.path.splitext(parsed.path)[1] or ".png"
  1931. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1932. os.close(tmp_fd)
  1933. try:
  1934. data = await self._download_attachment_bytes(image_url)
  1935. await asyncio.to_thread(_write_file_bytes, tmp_path, data)
  1936. except Exception as e:
  1937. logger.warning("Chatto: image download failed for %s: %s", image_url, e)
  1938. try:
  1939. os.unlink(tmp_path)
  1940. except OSError:
  1941. pass
  1942. return None, False
  1943. return tmp_path, True
  1944. local = image_url
  1945. if local.startswith("file://"):
  1946. local = _unquote(urlsplit(local).path)
  1947. return self.validate_media_delivery_path(local), False
  1948. async def send_multiple_images(
  1949. self,
  1950. chat_id: str,
  1951. images: list[tuple[str, str]],
  1952. metadata: dict[str, Any] | None = None,
  1953. human_delay: float = 0.0,
  1954. ) -> None:
  1955. """Send a batch of images as ONE message with several attachments.
  1956. The base implementation posts each image separately; a Chatto message
  1957. carries a list of attachment assets, so a batch belongs in a single
  1958. message (and a single notification).
  1959. ``human_delay`` is ignored deliberately — there is only one outbound
  1960. call to pace. Entries that can't be fetched are dropped with a warning;
  1961. if nothing survives, we fall back to the base class so the user still
  1962. gets the links.
  1963. BasePlatformAdapter override
  1964. """
  1965. if len(images or []) < 2:
  1966. await super().send_multiple_images(
  1967. chat_id,
  1968. images,
  1969. metadata=metadata,
  1970. human_delay=human_delay,
  1971. )
  1972. return
  1973. asset_ids: list[str] = []
  1974. captions: list[str] = []
  1975. for image_url, alt_text in images:
  1976. path, is_temp = await self._materialise_image(image_url)
  1977. if not path:
  1978. logger.warning("Chatto: skipping unusable image %s", image_url)
  1979. continue
  1980. try:
  1981. asset_id = await self._upload_asset(str(chat_id), path)
  1982. finally:
  1983. if is_temp:
  1984. try:
  1985. os.unlink(path)
  1986. except OSError:
  1987. pass
  1988. if not asset_id:
  1989. logger.warning("Chatto: upload failed for image %s", image_url)
  1990. continue
  1991. asset_ids.append(asset_id)
  1992. if alt_text:
  1993. captions.append(alt_text)
  1994. if not asset_ids:
  1995. logger.warning(
  1996. "Chatto: no image survived upload, falling back to per-image delivery",
  1997. )
  1998. await super().send_multiple_images(
  1999. chat_id,
  2000. images,
  2001. metadata=metadata,
  2002. human_delay=human_delay,
  2003. )
  2004. return
  2005. if len(asset_ids) < len(images):
  2006. logger.warning(
  2007. "Chatto: sending %d of %d images — the rest could not be uploaded",
  2008. len(asset_ids),
  2009. len(images),
  2010. )
  2011. await self._post_attachment_message(
  2012. chat_id,
  2013. asset_ids,
  2014. "\n".join(captions) or None,
  2015. None,
  2016. metadata,
  2017. )
  2018. # ---------------------------------------------------------------------------
  2019. # Cron / out-of-process delivery
  2020. # ---------------------------------------------------------------------------
  2021. async def hermes_standalone_sender_fn(
  2022. pconfig: PlatformConfig,
  2023. chat_id: str,
  2024. message: str,
  2025. *,
  2026. thread_id=None,
  2027. media_files=None,
  2028. force_document=False,
  2029. ) -> SendResult:
  2030. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  2031. Used by cron / scheduled routines that run out-of-process. Creates a
  2032. short-lived chattolib client, posts, and closes.
  2033. """
  2034. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  2035. # Create a temporary client for standalone sending — we need a base URL plus
  2036. # either a token or a full login/password pair.
  2037. has_credentials = bool(
  2038. chatto_config.token.value
  2039. or (chatto_config.login.value and chatto_config.password.value),
  2040. )
  2041. if not chatto_config.base_url.value or not has_credentials:
  2042. return SendResult(
  2043. success=False, error="Chatto: base URL or credentials missing"
  2044. )
  2045. client: ChattoClient
  2046. try:
  2047. if chatto_config.token.value:
  2048. client = ChattoClient(
  2049. base_url=chatto_config.base_url.value, token=chatto_config.token.value
  2050. )
  2051. else:
  2052. client = await ChattoClient.login(
  2053. base_url=chatto_config.base_url.value,
  2054. login=chatto_config.login.value,
  2055. password=chatto_config.password.value,
  2056. )
  2057. except Exception as exc:
  2058. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  2059. try:
  2060. kwargs: dict[str, Any] = {}
  2061. if chatto_config.auto_thread.value and thread_id:
  2062. kwargs["thread_root_event_id"] = thread_id
  2063. if media_files and media_files.get("attachment_asset_ids"):
  2064. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  2065. try:
  2066. posted = await client.post_message(chat_id, message, **kwargs)
  2067. except Exception as exc:
  2068. return SendResult(success=False, error=str(exc))
  2069. return SendResult(success=True, message_id=posted.id)
  2070. finally:
  2071. try:
  2072. await client.close()
  2073. except Exception as exc:
  2074. logger.error(
  2075. "Chatto standalone: error closing short-lived client (perhaps already closed): %s",
  2076. exc,
  2077. )
  2078. def hermes_validate_config(config: PlatformConfig) -> bool:
  2079. """Check whether Chatto Plugin is configured.
  2080. Function name should be the same as register argument name with "hermes_" prefix, so we
  2081. know that it is needed for plugin register(). Do not change signature.
  2082. Takes ``config``. Compare to hermes_is_connected().
  2083. """
  2084. chatto_config = ChattoConfiguration(pconfig=config)
  2085. if (
  2086. len(chatto_config.allowed_users.value) > 0
  2087. and chatto_config.allow_all_users.value
  2088. ):
  2089. logger.info(
  2090. "Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both."
  2091. )
  2092. return False
  2093. if chatto_config.base_url.value:
  2094. if (chatto_config.token.value is not None) or (
  2095. chatto_config.login.value and chatto_config.password.value
  2096. ):
  2097. return True
  2098. else:
  2099. logger.error(
  2100. "Chatto: Minimally, either token or login/password must be set."
  2101. )
  2102. else:
  2103. logger.error("Chatto: base_url must be set.")
  2104. return False
  2105. def hermes_check_fn() -> bool:
  2106. """Report whether the vendored chattolib dependency can be imported."""
  2107. try:
  2108. from chattolib import (
  2109. client, # noqa: F401 — vendored dependency probe
  2110. )
  2111. return True
  2112. except ImportError:
  2113. return False
  2114. # ---------------------------------------------------------------------------
  2115. # is_connected probe
  2116. # ---------------------------------------------------------------------------
  2117. def hermes_is_connected(config: PlatformConfig) -> bool:
  2118. """Check whether Chatto Plugin is connected. But where to: the Hermes Agent or the Chatto server.
  2119. The Hermes Agent plugin docs suck and it seems there are many functions to do the same.
  2120. """
  2121. return bool(hermes_validate_config(config) and config.enabled)
  2122. def hermes_setup_fn() -> None:
  2123. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  2124. Function name should be the same as register argument name with "hermes_" prefix, so we
  2125. know that it is needed for plugin register().
  2126. """
  2127. from hermes_cli.setup import (
  2128. print_success,
  2129. prompt,
  2130. prompt_yes_no,
  2131. save_env_value,
  2132. )
  2133. url = prompt(
  2134. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:"
  2135. )
  2136. if url:
  2137. save_env_value(ChattoConfiguration.base_url.env_name, url)
  2138. login = prompt("Chatto login (username):")
  2139. if login:
  2140. save_env_value(ChattoConfiguration.login.env_name, login)
  2141. password = prompt("Chatto password:", password=True)
  2142. if password:
  2143. save_env_value(ChattoConfiguration.password.env_name, password)
  2144. home = prompt("Home room ID for notifications (or empty):")
  2145. if home:
  2146. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  2147. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  2148. if allow_all:
  2149. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  2150. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  2151. def hermes_env_enablement_fn() -> dict | None:
  2152. """Seed PlatformConfig.extra from env vars.
  2153. Returns a dict compatible with the PlatformConfig merge hook (or None
  2154. when no env-provided values are present).
  2155. Called by the platform registry during load_gateway_config().
  2156. Return None when the platform isn't minimally configured — the
  2157. caller then skips auto-enabling. Return a dict to seed extras.
  2158. The special 'home_channel' key is extracted and becomes a proper
  2159. HomeChannel dataclass on the PlatformConfig; every other key is
  2160. merged into PlatformConfig.extra.
  2161. Function name should be the same as register argument name with "hermes_" prefix, so we
  2162. know that it is needed for plugin register().
  2163. """
  2164. # Seed keys must be the config.yaml "extra" keys (config_key), NOT the env
  2165. # var names — ChattoConfiguration reads extra[config_key].
  2166. seed: dict[str, Any] = {
  2167. ChattoConfiguration.base_url.field_name: (
  2168. os.getenv(ChattoConfiguration.base_url.env_name)
  2169. or ChattoClient.DEFAULT_BASE_URL
  2170. ).strip(),
  2171. }
  2172. for field in ChattoConfiguration.fields():
  2173. if field.field_name == ChattoConfiguration.base_url.field_name:
  2174. continue
  2175. env_value = os.getenv(field.env_name)
  2176. if env_value:
  2177. seed[field.config_key] = env_value.strip()
  2178. logger.debug(
  2179. "seed: %s", {k: v for k, v in seed.items() if k not in ("token", "password")}
  2180. )
  2181. return seed
  2182. # ---------------------------------------------------------------------------
  2183. # Plugin registration entry point
  2184. # ---------------------------------------------------------------------------
  2185. # What each capability is called in the startup banner, keyed by the method
  2186. # that implements it. Derived from real overrides rather than hard-coded, so
  2187. # dropping a method drops its claim from the log instead of leaving a lie.
  2188. _CAPABILITY_LABELS = {
  2189. "send": "text",
  2190. "send_image_file": "images",
  2191. "send_multiple_images": "image batches (bundled into one message)",
  2192. "send_video": "video",
  2193. "send_voice": "voice messages",
  2194. "send_document": "documents",
  2195. "add_reaction": "reactions",
  2196. "edit_message": "message editing",
  2197. "delete_message": "message deletion",
  2198. "send_typing": "typing indicators",
  2199. "create_handoff_thread": "threads",
  2200. "start_dm": "direct messages",
  2201. "create_room": "room creation",
  2202. }
  2203. def _capabilities() -> list[str]:
  2204. """Name the things this adapter genuinely implements itself.
  2205. A capability counts only when ChattoAdapter overrides the base method —
  2206. inheriting BasePlatformAdapter's fallback means the feature is not
  2207. natively supported, and announcing it would mislead.
  2208. """
  2209. found = [
  2210. label
  2211. for name, label in _CAPABILITY_LABELS.items()
  2212. if getattr(ChattoAdapter, name, None)
  2213. is not getattr(BasePlatformAdapter, name, None)
  2214. ]
  2215. if ChattoAdapter.supports_code_blocks:
  2216. found.append("code blocks")
  2217. if ChattoAdapter.supports_status_text:
  2218. found.append("custom status text")
  2219. found.append("presence (refreshed while connected)")
  2220. return found
  2221. def register(ctx) -> None:
  2222. """Plugin entry point — called by the Hermes plugin system."""
  2223. logger.info("Registering Chatto platform plugin on Hermes Agent")
  2224. for capability in _capabilities():
  2225. logger.info("Chatto capability: %s", capability)
  2226. logger.info(
  2227. "ChattoConfiguration.allowed_users.env_name: %s",
  2228. ChattoConfiguration.allowed_users.env_name,
  2229. )
  2230. ctx.register_platform(
  2231. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  2232. label=ChattoConstants.PLATFORM_LABEL,
  2233. adapter_factory=hermes_adapter_factory,
  2234. check_fn=hermes_check_fn,
  2235. validate_config=hermes_validate_config,
  2236. is_connected=hermes_is_connected,
  2237. install_hint=ChattoConstants.INSTALL_HINT,
  2238. env_enablement_fn=hermes_env_enablement_fn,
  2239. setup_fn=hermes_setup_fn,
  2240. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  2241. standalone_sender_fn=hermes_standalone_sender_fn,
  2242. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  2243. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  2244. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  2245. emoji="😺",
  2246. allow_update_command=True,
  2247. pii_safe=False,
  2248. platform_hint=(
  2249. "Using the 'Hermes Chatto Platform Plugin' you connect to a Chatto server. "
  2250. "Authorized admins and users will contact you and call you his Hermes Agent. They are "
  2251. "natural persons and thus responsible for what they do in terms of rights. You compute "
  2252. "on their behalf. They _may_ address you by @-mentioning your name. If configured, "
  2253. "you also react without a @-mention. Direct messages reach you without a mention."
  2254. "Keep responses conversational. Markdown is supported. "
  2255. "Include MEDIA:/absolute/path/to/file in your response to refer to our local files. Images "
  2256. "(.png, .jpg, .gif, .webp) arrive as inline pictures, videos (.mp4, .mov, .webm) as "
  2257. "video attachments, audio as a voice bubble, anything else as a downloadable document. "
  2258. "Do NOT use markdown image syntax for local files. Local files always go through MEDIA:. "
  2259. "Several images in one response are bundled into a single message. "
  2260. ),
  2261. )