adapter.py 110 KB

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