adapter.py 126 KB

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