adapter.py 125 KB

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