adapter.py 94 KB

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