adapter.py 111 KB

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