adapter.py 129 KB

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