adapter.py 132 KB

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