adapter.py 110 KB

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