adapter.py 121 KB

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