adapter.py 132 KB

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