adapter.py 130 KB

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