adapter.py 119 KB

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