adapter.py 116 KB

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