adapter.py 101 KB

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