adapter.py 110 KB

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