adapter.py 101 KB

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