adapter.py 111 KB

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