adapter.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  1. """
  2. Chatto Platform Adapter for Hermes Agent.
  3. A plugin-based gateway adapter that connects to a Chatto server
  4. (self-hosted team chat) and relays messages to/from the Hermes agent.
  5. The adapter uses the chattolib library for all Chatto API interactions,
  6. including both outbound messaging and realtime WebSocket connections.
  7. """
  8. from __future__ import annotations
  9. import inspect
  10. import random
  11. from gateway.platforms.helpers import MessageDeduplicator
  12. # Put the vendored dependencies for THIS platform on sys.path before importing
  13. # anything from chattolib. Imported relatively as part of the plugin package and
  14. # absolutely when this module is loaded standalone (e.g. by the tests).
  15. try:
  16. from .vendor_path import setup_vendor_path
  17. except ImportError: # pragma: no cover - depends on how the module is loaded
  18. from vendor_path import setup_vendor_path
  19. setup_vendor_path()
  20. import asyncio
  21. import hashlib
  22. import logging
  23. import mimetypes
  24. import os
  25. from datetime import datetime, timezone
  26. from enum import StrEnum
  27. from typing import Any, Dict, List, Literal, Optional, Tuple, cast
  28. from urllib.parse import urlsplit
  29. logger = logging.getLogger(__name__)
  30. from gateway.platforms.base import (
  31. BasePlatformAdapter,
  32. SendResult,
  33. MessageEvent,
  34. MessageType,
  35. ProcessingOutcome,
  36. cache_media_bytes,
  37. get_inbound_media_max_bytes,
  38. validate_inbound_media_size,
  39. )
  40. from gateway.config import Platform, PlatformConfig
  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. ChattoRealtimeError,
  58. ChattoRealtimeCloseError, RealtimeEvent,
  59. stream_events
  60. )
  61. from chattolib.realtime_types import (
  62. MessagePostedPayload,
  63. ReactionPayload,
  64. )
  65. from chattolib.types import (
  66. PresenceStatus, RoomKind, User
  67. )
  68. except ImportError as e:
  69. # Fail loudly: continuing here only defers the failure to a confusing
  70. # NameError somewhere deep in the adapter.
  71. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  72. raise
  73. try:
  74. from .platform_config import (
  75. ChattoConfiguration, ChattoConstants,
  76. )
  77. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  78. from platform_config import (
  79. ChattoConfiguration, ChattoConstants,
  80. )
  81. # --------------------------------------------------------------------------- #
  82. # Chat types
  83. # --------------------------------------------------------------------------- #
  84. class HermesChatType(StrEnum):
  85. """The ``chat_type`` vocabulary the Hermes gateway understands.
  86. Declared in ``gateway/session.py:161`` as ``"dm", "group", "channel",
  87. "thread"`` and consumed as a bare string all over the gateway:
  88. ``SessionSource.description`` (session.py:239) and the PII-redacting
  89. description in ``build_session_context_prompt`` (session.py:537) both
  90. branch on these exact values and fall back to a nameless generic case for
  91. anything else, and ``build_session_key`` puts the value straight into the
  92. session key. Passing a chattolib ``RoomKind`` (``"ROOM_KIND_CHANNEL"``)
  93. therefore does not fail loudly — it just quietly degrades what the agent is
  94. told about where it is.
  95. A StrEnum so it stays a drop-in ``str`` at every one of those call sites.
  96. GROUP vs CHANNEL
  97. ----------------
  98. There is no strict contract between the two, and the adapters disagree in
  99. practice: Slack labels every non-DM conversation ``"group"`` (including real
  100. channels), Discord uses both, and Telegram reserves ``"channel"`` for actual
  101. broadcast channels. The intended reading is ``group`` = ordinary
  102. multi-participant chat, ``channel`` = broadcast surface.
  103. The distinction only changes behaviour in three places:
  104. 1. Authorization (``gateway/authz_mixin.py``) — the only security-relevant
  105. one. The group-scoped env allowlists apply to ``{"group", "forum"}``
  106. ONLY, never to ``"channel"``: ``{PLATFORM}_GROUP_ALLOWED_USERS`` /
  107. ``_GROUP_ALLOWED_CHATS`` (:616), the chat-id allowlist (:708) and the
  108. Telegram legacy shim (:724). The adapter-delegation paths in turn treat
  109. all three alike (:461, :649, :674, :694), where the value only picks
  110. ``group_allow_from`` over ``allow_from`` from ``config.extra``.
  111. For Chatto both choices are equivalent today: those group env maps hold
  112. Telegram and QQBot only (:535-541), and our own allowlist runs through
  113. ``CHATTO_ALLOWED_USERS``, which is chat_type-independent.
  114. 2. What the agent is told — ``SessionSource.description`` renders
  115. ``"group: Name"`` vs ``"channel: Name"`` (session.py:239-246), likewise
  116. the PII-redacted variant (session.py:537-544).
  117. 3. The session key, which embeds the literal (session.py:1192). Changing
  118. the value for a room re-buckets its existing sessions.
  119. Explicitly NOT affected: ``is_shared_multi_user_session`` (session.py:1063)
  120. only looks at ``"dm"`` and ``thread_id``, so sender prefixes, the multi-user
  121. prompt line and ``group_sessions_per_user`` treat group and channel
  122. identically.
  123. """
  124. DM = "dm"
  125. GROUP = "group"
  126. CHANNEL = "channel"
  127. # Emitted by adapters whose thread events are their own chat type (Slack,
  128. # Discord). We don't: a Chatto thread keeps its room's chat_type and is
  129. # identified by ``thread_id`` on the source instead. Listed for the record,
  130. # because build_session_key rewrites the slot to "thread" itself
  131. # (session.py:1190).
  132. THREAD = "thread"
  133. # Not declared in session.py:161 but real: Telegram forum topics travel as
  134. # "forum", and the authz group allowlists above accept it alongside "group".
  135. # Chatto has no equivalent, so we never emit it.
  136. # Chatto only distinguishes DMs from channels. UNSPECIFIED means the server
  137. # sent a kind this vendored chattolib doesn't know: map it to the generic
  138. # multi-user bucket rather than guessing "channel", and never to "dm" — that
  139. # value drives session isolation (is_shared_multi_user_session, session.py:1063)
  140. # and would silently turn a room into a private conversation.
  141. #
  142. # CHANNEL for RoomKind.CHANNEL is the descriptive choice and carries no
  143. # behavioural cost (see the GROUP vs CHANNEL note above). Switching to GROUP for
  144. # Slack parity would be this one line — plus the re-bucketing of existing
  145. # sessions that point 3 of that note describes.
  146. _ROOM_KIND_TO_CHAT_TYPE: Dict[RoomKind, HermesChatType] = {
  147. RoomKind.DM: HermesChatType.DM,
  148. RoomKind.CHANNEL: HermesChatType.CHANNEL,
  149. RoomKind.UNSPECIFIED: HermesChatType.GROUP,
  150. }
  151. def chat_type_for_room_kind(kind: Optional[RoomKind]) -> HermesChatType:
  152. """Map a chattolib RoomKind onto the gateway's chat_type vocabulary.
  153. An unknown or missing kind becomes ``GROUP`` — see ``_ROOM_KIND_TO_CHAT_TYPE``.
  154. """
  155. if kind is None:
  156. return HermesChatType.GROUP
  157. return _ROOM_KIND_TO_CHAT_TYPE.get(kind, HermesChatType.GROUP)
  158. # --------------------------------------------------------------------------- #
  159. # Adapter
  160. # --------------------------------------------------------------------------- #
  161. def hermes_adapter_factory(config: PlatformConfig):
  162. """Factory wrapper that constructs ChattoAdapter from a PlatformConfig."""
  163. return ChattoAdapter(config)
  164. class ChattoAdapter(BasePlatformAdapter):
  165. """Chatto platform adapter — receives messages via WebSocket realtime,
  166. sends via ConnectRPC."""
  167. _SPLIT_THRESHOLD = 9900
  168. # Read by BasePlatformAdapter.max_message_length_for_chat(), which the
  169. # gateway and the stream consumer use to chunk outgoing messages. Without
  170. # it they fall back to 4096 and split Chatto messages far earlier than
  171. # necessary — send() itself already truncates at 10000.
  172. MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  173. splits_long_messages = True
  174. supports_code_blocks: bool = True
  175. supports_status_text: bool = True # client.update_custom_status
  176. def __init__(self, pconfig: PlatformConfig):
  177. """Signature needs to be compatible with BasePlatformAdapter.__init__ """
  178. super().__init__(config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME))
  179. # "extra" has been pre-processed by Hermes-Framework to be a dict of extra config values insode PlatformConfig.
  180. # --- Configuration from our configuration data class with some logic ---
  181. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  182. # ------ State -------
  183. # SDK runtime handle (injected by Hermes); annotate for Pylance
  184. self.sdk: Any = getattr(self, "sdk", None)
  185. # Our own user, filled in by connect(). Events arriving before connect()
  186. # completes must not blow up on an undefined attribute.
  187. self.me: Optional[User] = None
  188. # --- Runtime state ---
  189. self._user_id: str = ""
  190. self._user_display: str = ""
  191. self._room_names: Dict[str, str] = {}
  192. self._room_kinds: Dict[str, RoomKind] = {}
  193. self._our_thread_roots: set = set() # thread root event IDs we created
  194. self._our_message_ids: set = set() # message IDs we sent (for thread root detection)
  195. self._seen: list[str] = [] # Plain RealtimeEvent-id list
  196. self._resume_cursor: Optional[str] = None
  197. self._watch_room_ids: List[str] = []
  198. self._ws_task: Optional[asyncio.Task] = None
  199. self._presence_task: Optional[asyncio.Task] = None
  200. self._ws_ready: Optional[asyncio.Event] = None
  201. self._ws_active = False
  202. self._ws_ref = None # reference to open websocket for dynamic resubscribe
  203. # Persistent typing indicator loops per room
  204. self._typing_tasks: Dict[str, asyncio.Task] = {}
  205. # Member directory cache: user_id -> user info dict
  206. self._user_cache: Dict[str, User] = {}
  207. # Chattolib client cache and lock for async access.
  208. self._chatto_client: Optional[ChattoClient] = None
  209. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  210. # Dedup — chattolib may redeliver events across reconnects.
  211. self._dedup = MessageDeduplicator()
  212. def _list_functions(self):
  213. for name, member in inspect.getmembers(self, predicate=callable):
  214. # filtert dunder-Methoden falls gewünscht
  215. if not name.startswith('__'):
  216. logger.info("functions: %s", name)
  217. # ------------------------------------------------------------------ #
  218. # Auth
  219. # ------------------------------------------------------------------ #
  220. async def _get_chatto_client(self: ChattoAdapter) -> Optional[ChattoClient]:
  221. """Get or create a ChattoClient instance."""
  222. if self._chatto_client is not None:
  223. return self._chatto_client
  224. async with self._chatto_client_lock:
  225. if self._chatto_client is not None:
  226. return self._chatto_client
  227. try:
  228. assert(self.chatto_config.login.value) # now we can assume, _login is available.
  229. client = await self._open_client(
  230. base_url=self.chatto_config.base_url.value,
  231. login=self.chatto_config.login.value,
  232. password=self.chatto_config.password.value,
  233. token=self.chatto_config.token.value,
  234. )
  235. self._chatto_client = client
  236. self._token = client.token
  237. logger.info("Chatto: logged in as '%s' via chattolib", self.chatto_config.login.value)
  238. return client
  239. except ChattoAuthError as e:
  240. logger.error("Chatto: authentication failed: %s", e)
  241. return None
  242. except (ChattoError, ValueError) as e:
  243. logger.error("Chatto: failed to create client: %s", e)
  244. return None
  245. async def _require_client(self) -> ChattoClient:
  246. """Return a ChattoClient or raise RuntimeError if unavailable.
  247. Use this helper when the caller expects a client to exist and
  248. wants a single canonical failure path. Methods that prefer a
  249. soft-fail can catch RuntimeError and return gracefully.
  250. """
  251. client = await self._get_chatto_client()
  252. if client is None:
  253. raise RuntimeError("Chatto client unavailable")
  254. return client
  255. async def _ensure_token(self) -> bool:
  256. """Ensure we have a logged-in Chatto client and token."""
  257. if self.chatto_config.token.value and isinstance(self._chatto_client, ChattoClient):
  258. return True
  259. client = await self._get_chatto_client()
  260. return client is not None
  261. async def _relogin(self) -> bool:
  262. """Force re-login (token expired)."""
  263. self._token = None
  264. return await self._ensure_token()
  265. # ------------------------------------------------------------------ #
  266. # Connection
  267. # ------------------------------------------------------------------ #
  268. async def _open_client(
  269. self,
  270. *,
  271. base_url: str,
  272. login: str,
  273. password: str,
  274. token: Optional[str] = None,
  275. ) -> ChattoClient:
  276. """Return a connected ``ChattoClient`` using token or login/password."""
  277. if token:
  278. return ChattoClient(token=token, base_url=base_url)
  279. return await ChattoClient.login(login, password, base_url=base_url)
  280. async def connect(self, *, is_reconnect: bool = False) -> bool:
  281. """Connect to Chatto and start the realtime event stream.
  282. BasePlatformAdapter override
  283. """
  284. logger.info("Chatto: connecting...")
  285. if not await self._ensure_token():
  286. return False
  287. try:
  288. client = await self._require_client()
  289. except RuntimeError:
  290. self._set_fatal_error("connect_failed", "Chatto client not available", retryable=True)
  291. return False
  292. # Get our first own user info
  293. try:
  294. self.me = await client.me()
  295. except Exception as exc:
  296. logger.error("Chatto: failed to get user info: %s", exc)
  297. self._set_fatal_error(
  298. "chatto_auth_failed",
  299. f"Chatto auth failed: {exc}",
  300. retryable=False,
  301. )
  302. try:
  303. assert(self._chatto_client)
  304. await self._chatto_client.close()
  305. finally:
  306. self._chatto_client = None
  307. return False
  308. # Announce online presence so the bot appears online in the member list.
  309. # The server treats this as a TTL, so _presence_refresh_loop below has to
  310. # keep re-announcing it — a single call here lapses back to offline.
  311. await self._announce_online()
  312. self._closing = False
  313. # Start background realtime WS event stream loop.
  314. self._ws_ready = asyncio.Event()
  315. self._ws_task = asyncio.create_task(
  316. self._chattolib_event_loop(), name="chatto-event-stream",
  317. )
  318. self._presence_task = asyncio.create_task(
  319. self._presence_refresh_loop(), name="chatto-presence-refresh",
  320. )
  321. self._mark_connected()
  322. self._list_functions()
  323. logger.info(
  324. "Chatto: connected and authentiated to %s using login:'%s' (display_name:'%s' id: '%s')",
  325. self.chatto_config.base_url.value,
  326. self.me.login, self.me.display_name, self.me.id
  327. )
  328. return True
  329. async def _announce_online(self) -> bool:
  330. """Tell the server we are online. Returns whether the call got through.
  331. Logged at warning level on failure: a silently dropped presence call is
  332. indistinguishable from a bot that is simply not running.
  333. """
  334. try:
  335. client = await self._require_client()
  336. await client.update_presence(status=PresenceStatus.ONLINE)
  337. return True
  338. except Exception as exc:
  339. logger.warning("Chatto: presence refresh failed, bot may appear offline: %s", exc)
  340. return False
  341. async def _presence_refresh_loop(self) -> None:
  342. """Re-announce ONLINE until disconnect, since presence expires server-side.
  343. Failures are not fatal — the next tick tries again, so a blip in the
  344. presence endpoint costs at most one interval of visible offline time.
  345. """
  346. while not self._closing:
  347. await self._sleep_interruptible(ChattoConstants.PRESENCE_REFRESH_INTERVAL)
  348. if self._closing:
  349. return
  350. await self._announce_online()
  351. async def disconnect(self) -> None:
  352. """Stop WebSocket, presence refresh, typing tasks, and clear state.
  353. BasePlatformAdapter override
  354. """
  355. # No explicit offline broadcast: chattolib rejects OFFLINE outright
  356. # ("stop refreshing to go offline"), so cancelling the refresh loop
  357. # below is what actually takes the bot offline.
  358. self._ws_active = False
  359. self._closing = True
  360. # Cancel all typing tasks
  361. for chat_id in list(self._typing_tasks.keys()):
  362. await self.stop_typing(chat_id)
  363. if self._ws_task and not self._ws_task.done():
  364. self._ws_task.cancel()
  365. try:
  366. await self._ws_task
  367. except (asyncio.CancelledError, Exception):
  368. pass
  369. self._ws_task = None
  370. if self._presence_task and not self._presence_task.done():
  371. self._presence_task.cancel()
  372. try:
  373. await self._presence_task
  374. except (asyncio.CancelledError, Exception):
  375. pass
  376. self._presence_task = None
  377. if self._chatto_client:
  378. try:
  379. await self._chatto_client.close()
  380. except Exception:
  381. logger.exception("Chatto: error closing client")
  382. finally:
  383. self._chatto_client = None
  384. self._token = None
  385. logger.info("Chatto: disconnected")
  386. self._mark_disconnected()
  387. async def _seed_room(self, room_id: str) -> None:
  388. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  389. try:
  390. try:
  391. client = await self._require_client()
  392. timeline_page = await client.get_room_events(room_id)
  393. except RuntimeError:
  394. logger.debug("Chatto: _seed_room aborted - no client available for %s", room_id)
  395. return
  396. for ev in timeline_page.events:
  397. if ev.id:
  398. self._mark_seen(ev.id)
  399. logger.debug("Chatto: seeded room %s with %d events", room_id, len(timeline_page.events))
  400. except Exception as e:
  401. logger.debug("Chatto: get room events failed for %s: %s", room_id, e)
  402. # ------------------------------------------------------------------ #
  403. # Realtime Event List
  404. # ------------------------------------------------------------------ #
  405. def _mark_seen(self, event_id: str) -> None:
  406. self._seen.append(event_id)
  407. while len(self._seen) > ChattoConstants.SEEN_CAP:
  408. self._seen.remove(self._seen[0]) # fastest removal of first item in a list.
  409. def _is_seen(self, event_id: str) -> bool:
  410. return event_id in self._seen
  411. # ------------------------------------------------------------------ #
  412. # WebSocket Realtime Transport
  413. # ------------------------------------------------------------------ #
  414. def _check_auth(self, user: User) -> bool:
  415. """We roll our own auth-systen on the against the chatto_config'ured allowed_users etc.
  416. because.. Hermes authz_mixin.py IS NOT SANE.
  417. """
  418. if self.chatto_config.allow_all_users.value:
  419. return True
  420. if user.login in self.chatto_config.allowed_users.value:
  421. return True
  422. if user.id in self.chatto_config.allowed_users.value:
  423. return True
  424. logger.info("Chatto: rejecting message from unauthorized user '%s' (%s)", user.login, user.id)
  425. return False
  426. # ------------------------------------------------------------------ #
  427. # Inbound attachments
  428. # ------------------------------------------------------------------ #
  429. async def _download_attachment_bytes(self, url: str) -> bytes:
  430. """Download an attachment, refusing to buffer more than the gateway cap.
  431. The Content-Length header is checked first so an oversized asset is
  432. rejected before a single chunk is read; the running total is re-checked
  433. as chunks arrive, because a missing or lying header must not smuggle an
  434. unbounded body past the cap.
  435. """
  436. import httpx
  437. max_bytes = get_inbound_media_max_bytes()
  438. chunks: List[bytes] = []
  439. total = 0
  440. async with httpx.AsyncClient(
  441. timeout=ChattoConstants.HTTP_TIMEOUT, follow_redirects=True,
  442. ) as http:
  443. async with http.stream("GET", url) as resp:
  444. resp.raise_for_status()
  445. declared = resp.headers.get("content-length")
  446. if declared:
  447. try:
  448. declared_size = int(declared)
  449. except ValueError:
  450. logger.debug("Chatto: ignoring invalid Content-Length %r", declared)
  451. else:
  452. validate_inbound_media_size(
  453. declared_size, media_type="attachment", max_bytes=max_bytes,
  454. )
  455. async for chunk in resp.aiter_bytes():
  456. total += len(chunk)
  457. validate_inbound_media_size(
  458. total, media_type="attachment", max_bytes=max_bytes,
  459. )
  460. chunks.append(chunk)
  461. return b"".join(chunks)
  462. async def _cache_attachments(
  463. self, room_id: str, attachments: List[Any],
  464. ) -> Tuple[List[str], List[str], List[str]]:
  465. """Download message attachments into the gateway media cache.
  466. Returns ``(media_urls, media_types, media_kinds)`` — the paths are
  467. agent-visible cache paths, exactly what ``cache_media_bytes`` yields for
  468. every other platform. A failing attachment is logged and skipped: the
  469. message itself still reaches the agent.
  470. """
  471. media_urls: List[str] = []
  472. media_types: List[str] = []
  473. media_kinds: List[str] = []
  474. for att in attachments or []:
  475. asset_url = getattr(att, "asset_url", None)
  476. url = getattr(asset_url, "url", "") if asset_url else ""
  477. filename = getattr(att, "filename", "") or ""
  478. content_type = getattr(att, "content_type", "") or ""
  479. if not url:
  480. # Videos are announced before transcoding finishes, so the
  481. # signed URL can legitimately be missing on arrival.
  482. logger.info(
  483. "Chatto: attachment '%s' has no asset URL yet, skipping", filename,
  484. )
  485. continue
  486. try:
  487. data = await self._download_attachment_bytes(url)
  488. cached = cache_media_bytes(
  489. data, filename=filename, mime_type=content_type,
  490. )
  491. except Exception as e:
  492. logger.warning(
  493. "Chatto: failed to cache attachment '%s' (%s): %s",
  494. filename, content_type, e,
  495. )
  496. continue
  497. if cached is None:
  498. logger.warning(
  499. "Chatto: attachment '%s' (%s) could not be cached, skipping",
  500. filename, content_type,
  501. )
  502. continue
  503. media_urls.append(cached.path)
  504. media_types.append(cached.media_type)
  505. media_kinds.append(cached.kind)
  506. return media_urls, media_types, media_kinds
  507. @staticmethod
  508. def _message_type_for_media_kinds(media_kinds: List[str]) -> MessageType:
  509. """Pick the MessageType for a set of cached attachment kinds."""
  510. if "document" in media_kinds:
  511. return MessageType.DOCUMENT
  512. if "image" in media_kinds:
  513. return MessageType.PHOTO
  514. if "video" in media_kinds:
  515. return MessageType.VIDEO
  516. if "audio" in media_kinds:
  517. return MessageType.AUDIO
  518. return MessageType.TEXT
  519. async def _dispatch_message_posted(self, payload: MessagePostedPayload) -> None:
  520. try:
  521. client = await self._require_client()
  522. except RuntimeError:
  523. logger.warning("Chatto: chattolib event loop aborted - no client available")
  524. return
  525. logger.info("Chatto WS: 'message_posted' event_payload:%s", payload)
  526. message = await payload.fetch_message(client=client)
  527. if message is None or message.deleted_at:
  528. return
  529. message_body = message.body or ""
  530. attachments = list(message.attachments or [])
  531. # A message carrying only an image/PDF has an empty body — dropping it
  532. # here is what made attachments sent to Hermes disappear silently.
  533. if not message_body and not attachments:
  534. return
  535. if message.actor_id in self._user_cache:
  536. # try the user cache.
  537. user = self._user_cache.get(message.actor_id)
  538. else:
  539. # get the user and update cache.
  540. directory_member = await client.get_user(user_id=message.actor_id)
  541. if directory_member is None:
  542. return
  543. user = directory_member.user
  544. if user is None:
  545. return
  546. self._user_cache[user.id] = user
  547. if user is None:
  548. return
  549. if not self._check_auth(user):
  550. return
  551. # Todo: use a function that either reads from cache or gets room kind again.
  552. if self._room_kinds.get(message.room_id) is None:
  553. room_viewer_state = await client.get_room(message.room_id)
  554. if room_viewer_state is None:
  555. return
  556. if room_viewer_state.room is None:
  557. return
  558. self._room_kinds[message.room_id] = room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  559. room_kind = self._room_kinds.get(message.room_id)
  560. logger.info("message_body: %s room_kind: %s", message_body, room_kind)
  561. # require_mention deliberately gates channels only: in a channel the bot
  562. # is one of many listeners and must be addressed, whereas a DM is already
  563. # addressed at it — so DMs are always answered, mention or not.
  564. mentioned = False
  565. if (room_kind == RoomKind.CHANNEL and self.chatto_config.require_mention.value and self.me):
  566. if self.me.login and not mentioned:
  567. mentioned = bool(f"@{self.me.login}" in message_body)
  568. if self.me.display_name and not mentioned:
  569. mentioned = bool(f"@{self.me.display_name}" in message_body)
  570. if mentioned is False:
  571. logger.debug("Discarding message. Bot was not mentionend but require_mention is '%s'.", self.chatto_config.require_mention.value)
  572. return
  573. logger.info("mentioned: %s", mentioned)
  574. # Thread anchoring — if the incoming message is inside a thread, we
  575. # keep that thread by default; otherwise leave thread_id unset so
  576. # replies land at the root.
  577. thread_id = payload.thread_root_event_id or None
  578. if not thread_id and room_kind != RoomKind.DM and self.chatto_config.auto_thread.value:
  579. thread_id = message.id
  580. source = self.build_source(
  581. chat_id=payload.room_id,
  582. chat_name=self._room_names.get(message.room_id),
  583. chat_type=chat_type_for_room_kind(room_kind),
  584. user_id=message.actor_id,
  585. user_name=user.login, # use login, because display_name is changeable by anyone.
  586. thread_id=thread_id,
  587. message_id=payload.message_event_id,
  588. role_authorized=True,
  589. )
  590. msg_type = MessageType.COMMAND if (message_body.lstrip().startswith("/")) else MessageType.TEXT
  591. my_body = message_body.lstrip() if msg_type == MessageType.COMMAND else message_body
  592. # Attachments — download and hand the local cache paths to the gateway,
  593. # which runs vision enrichment / document extraction off media_urls.
  594. media_urls, media_types, media_kinds = await self._cache_attachments(
  595. payload.room_id, attachments,
  596. )
  597. if media_kinds and msg_type != MessageType.COMMAND:
  598. # Same precedence as the Teams/Signal adapters: document-context
  599. # injection gates strictly on DOCUMENT, image handling keys off the
  600. # per-path image/* MIME regardless of message_type.
  601. msg_type = self._message_type_for_media_kinds(media_kinds)
  602. message_event = MessageEvent(
  603. text=my_body,
  604. source=source,
  605. message_id=message.id,
  606. message_type=msg_type,
  607. media_urls=media_urls,
  608. media_types=media_types,
  609. timestamp=message.created_at or datetime.now(timezone.utc),
  610. raw_message=message,
  611. reply_to_message_id=message.id,
  612. reply_to_text=message_body,
  613. reply_to_author_id=user.id,
  614. reply_to_author_name=user.login,
  615. )
  616. logger.info("Chatto: Dispatching MessageEvent to Hermes: %s", message_event)
  617. await self.handle_message(message_event)
  618. return
  619. async def _forward_reaction(
  620. self, event: RealtimeEvent, payload: ReactionPayload, *, removed: bool,
  621. ) -> None:
  622. """Forward a human reaction to the gateway's reaction hook surface.
  623. The handler is registered by the gateway via ``set_reaction_handler``
  624. and fans out as ``reaction:added`` / ``reaction:removed`` through the
  625. HookRegistry. The dict shape mirrors the Slack adapter's — hook
  626. consumers are written against that contract, not against a per-platform
  627. one. Our own lifecycle reactions (👀/✅/❌) are dropped: forwarding them
  628. would feed the agent its own markers.
  629. """
  630. actor_id = event.actor_id
  631. if actor_id and self.me and actor_id == self.me.id:
  632. return
  633. if not payload.room_id or not payload.message_event_id or not actor_id:
  634. return
  635. handler = getattr(self, "_reaction_handler", None)
  636. if handler is None:
  637. return
  638. action = "removed" if removed else "added"
  639. try:
  640. await handler(
  641. {
  642. "platform": ChattoConstants.PLATFORM_NAME,
  643. "event_name": f"reaction:{action}",
  644. "reaction": payload.emoji,
  645. "user_id": actor_id,
  646. "item_user_id": None,
  647. "item_type": "message",
  648. "channel_id": payload.room_id,
  649. "message_ts": payload.message_event_id,
  650. "event_ts": event.id,
  651. "raw_event": event,
  652. }
  653. )
  654. except Exception: # pragma: no cover - the hook contract is non-blocking
  655. logger.debug("Chatto: reaction hook forwarding failed", exc_info=True)
  656. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  657. if self._is_seen(event.id):
  658. return
  659. if event.actor_id is None:
  660. return
  661. logger.info("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  662. if (event_payload := event.get("message_posted")) is not None:
  663. # Self-event filter — the actor_id on the envelope is authoritative
  664. # (chattolib does NOT filter this itself; see chatto-bridge notes).
  665. actor_id = event.actor_id
  666. if actor_id and self.me and actor_id == self.me.id:
  667. return
  668. await self._dispatch_message_posted(event_payload)
  669. elif event.kind in ("reaction_added", "reaction_removed"):
  670. reaction_payload = event.get(event.kind)
  671. if reaction_payload is not None:
  672. await self._forward_reaction(
  673. event,
  674. cast(ReactionPayload, reaction_payload),
  675. removed=event.kind == "reaction_removed",
  676. )
  677. # confirmed:
  678. elif event.kind in ("mention_notification", "projection_event", "presence_changed", "notification_dismissed",
  679. "room_marked_as_read", "user_typing", "notification_created", "new_direct_message_notification",
  680. "message_edited", "message_retracted"):
  681. logger.debug("Chatto: '%s' event received. Not yet implemented or not needed.", event.kind)
  682. else:
  683. logger.error("Chatto: unknown event kind: '%s'", event.kind)
  684. async def _chattolib_event_loop(self) -> None:
  685. """Event loop using chattolib's stream_events.
  686. This replaces the manual WebSocket loop with chattolib's high-level
  687. stream_events() which provides pre-decoded RealtimeEvent objects.
  688. """
  689. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  690. while not self._closing:
  691. try:
  692. client = await self._require_client()
  693. await self._refresh_rooms()
  694. logger.info("Chatto: starting chattolib event stream with %d rooms", len(self._watch_room_ids))
  695. async for event in stream_events(client):
  696. if self._closing:
  697. return
  698. await self._handle_realtime_event(event)
  699. # Iterator exited cleanly — treat as a normal close and reconnect
  700. # with the local backoff (no server hint available).
  701. logger.info("Chatto: realtime stream ended, reconnecting")
  702. except asyncio.CancelledError:
  703. return
  704. except ChattoRealtimeCloseError as exc:
  705. if not exc.reconnect:
  706. logger.error(
  707. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  708. exc.code, exc.message,
  709. )
  710. return
  711. wait = max(exc.retry_after_ms / 1000.0, ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF)
  712. logger.warning(
  713. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  714. exc.code, wait,
  715. )
  716. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF # server hint supersedes local backoff
  717. await self._sleep_interruptible(wait)
  718. continue
  719. except ChattoRealtimeError as exc:
  720. if getattr(exc, "fatal", False):
  721. logger.error("Chatto: fatal realtime error (%s): %s", exc.code, exc.message)
  722. return
  723. logger.warning(
  724. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  725. exc.code, exc.message, delay,
  726. )
  727. except Exception as exc:
  728. logger.warning(
  729. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  730. exc, delay,
  731. )
  732. if self._closing:
  733. return
  734. jitter = delay * 0.2 * random.random()
  735. await self._sleep_interruptible(delay + jitter)
  736. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  737. async def _sleep_interruptible(self, seconds: float) -> None:
  738. """Sleep in short slices so disconnect() cancels promptly."""
  739. end = asyncio.get_running_loop().time() + seconds
  740. while not self._closing:
  741. remaining = end - asyncio.get_running_loop().time()
  742. if remaining <= 0:
  743. return
  744. await asyncio.sleep(min(remaining, 0.5))
  745. async def _refresh_rooms(self) -> None:
  746. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms."""
  747. try:
  748. client = await self._require_client()
  749. except RuntimeError:
  750. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  751. return
  752. try:
  753. rooms_list = await client.list_rooms()
  754. new_room_ids: List[str] = []
  755. for room_with_state in rooms_list:
  756. if not room_with_state:
  757. continue
  758. room_obj = room_with_state.room or None
  759. if not room_obj:
  760. continue
  761. self._room_names[room_obj.id] = room_obj.name
  762. self._room_kinds[room_obj.id] = room_obj.kind
  763. if room_with_state.viewer_state.is_member and room_obj.id not in self._watch_room_ids:
  764. new_room_ids.append(room_obj.id)
  765. if not new_room_ids:
  766. return
  767. logger.info("Chatto WS: discovered %d new room(s): %s", len(new_room_ids), new_room_ids)
  768. for rid in new_room_ids:
  769. if self._room_kinds.get(rid) != RoomKind.DM:
  770. await client.join_room(rid) # but list_rooms() would not return any if we were not already joined?!
  771. await self._seed_room(rid)
  772. self._watch_room_ids.append(rid)
  773. watch_room_names: list[str] = []
  774. for rid in self._watch_room_ids:
  775. watch_room_names.append(self._room_names[rid] + " (" + rid + ")")
  776. logger.info("Chatto WS: Watching %d room(s): %s", len(self._watch_room_ids), ", ".join(watch_room_names))
  777. except Exception:
  778. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  779. # ------------------------------------------------------------------ #
  780. # Read state & notification dismissal (best-effort, Chatto-unique)
  781. # ------------------------------------------------------------------ #
  782. # Best-effort: mark all watched rooms as read (room_id may be undefined here)
  783. for _rid in list(self._watch_room_ids):
  784. try:
  785. await client.mark_room_as_read(room_id=_rid)
  786. await client.dismiss_all_notifications()
  787. except Exception:
  788. logger.debug("Chatto: mark_room_as_read failed for %s", _rid, exc_info=True)
  789. # ------------------------------------------------------------------ #
  790. # Sending (ConnectRPC — unchanged from polling version)
  791. # ------------------------------------------------------------------ #
  792. async def send(
  793. self,
  794. chat_id: str,
  795. content: str,
  796. reply_to: Optional[str] = None,
  797. metadata: Optional[Dict[str, Any]] = None,
  798. ) -> SendResult:
  799. """Send a message to a Chatto room.
  800. Long messages are split into chunks via ``truncate_message`` and
  801. each chunk is sent as a separate CreateMessage call. The first
  802. chunk's message ID is returned as ``message_id``.
  803. When ``auto_thread`` is enabled and the incoming message was a
  804. regular room message (not already in a thread), the first chunk is
  805. sent as a room message and its ID becomes the thread root. Subsequent
  806. chunks are sent in that thread. This mirrors Discord's auto_thread
  807. behavior.
  808. BasePlatformAdapter override
  809. """
  810. if not content:
  811. return SendResult(success=False, error="Empty message")
  812. formatted = self.format_message(content)
  813. chunks = self.truncate_message(formatted, ChattoConstants.MAX_MESSAGE_LENGTH)
  814. # Thread support — resolve thread_id once
  815. # DM rooms don't support threads, so skip threading for DMs
  816. thread_id = (metadata or {}).get("thread_id")
  817. # Only use reply_to as thread_id if auto_thread is enabled.
  818. # When auto_thread=false, responses go directly in the room
  819. # without threading under the incoming message.
  820. if reply_to and self.chatto_config.auto_thread.value:
  821. # reply_to might be the incoming message ID. If we already have
  822. # thread_id from metadata, keep it (it's the thread root).
  823. # Only use reply_to as thread_id if we don't already have one.
  824. if not thread_id:
  825. thread_id = reply_to
  826. # Check if this is a DM room — DMs don't support threads
  827. room_kind = self._room_kinds.get(chat_id)
  828. is_dm = room_kind == RoomKind.DM
  829. if is_dm:
  830. thread_id = None
  831. # Auto-thread: by default, Chatto creates a thread for replies to room
  832. # messages (not DMs, not already in a thread). This keeps conversations
  833. # organized in the room. Can be disabled via extra.auto_thread=false.
  834. use_auto_thread = self.chatto_config.auto_thread.value and not thread_id and not is_dm
  835. message_ids: List[str] = []
  836. last_resp: Optional[Any] = None
  837. last_error: Optional[str] = None
  838. retryable = False
  839. try:
  840. client = await self._require_client()
  841. except RuntimeError:
  842. return SendResult(success=False, error="Chatto client not available", retryable=True)
  843. for i, chunk in enumerate(chunks):
  844. try:
  845. msg_obj = await client.post_message(
  846. room_id=chat_id,
  847. body=chunk,
  848. thread_root_event_id=str(thread_id) if thread_id else "",
  849. )
  850. except ChattoError as e:
  851. last_error = str(e)
  852. retryable = True
  853. break
  854. except Exception as e:
  855. last_error = str(e)
  856. retryable = True
  857. break
  858. last_resp = msg_obj
  859. self._mark_seen(msg_obj.id)
  860. message_ids.append(msg_obj.id)
  861. self._our_message_ids.add(msg_obj.id)
  862. # If we sent a message WITHOUT a thread_id, this message could
  863. # become a thread root if someone replies to it
  864. if not thread_id:
  865. self._our_thread_roots.add(msg_obj.id)
  866. # Auto-thread: first chunk becomes the thread root,
  867. # subsequent chunks go in the thread
  868. if use_auto_thread and i == 0 and not thread_id:
  869. thread_id = msg_obj.id
  870. # Nothing got through at all — report the failure instead of a phantom success.
  871. if not message_ids:
  872. return SendResult(
  873. success=False,
  874. error=last_error or "Chatto: message could not be sent",
  875. retryable=retryable,
  876. )
  877. first_id = message_ids[0]
  878. # ------------------------------------------------------------------ #
  879. # Thread following (best-effort, Chatto-unique)
  880. # ------------------------------------------------------------------ #
  881. if thread_id:
  882. try:
  883. await client.follow_thread(chat_id, thread_id)
  884. except Exception:
  885. logger.debug("Chatto: follow_thread failed for %s/%s", chat_id, thread_id, exc_info=True)
  886. # A later chunk failed after earlier ones went out: partial delivery.
  887. if last_error:
  888. logger.warning(
  889. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  890. len(message_ids), len(chunks), chat_id, last_error,
  891. )
  892. return SendResult(success=True, message_id=first_id, raw_response=last_resp)
  893. def format_message(self, content: str) -> str:
  894. """Normalise outgoing text for Chatto.
  895. Chatto renders Markdown natively, so there is nothing to escape or
  896. translate — the only transformations here are the ones that measurably
  897. render wrong: CRLF line endings (which show up as stray blank lines)
  898. and runs of more than two blank lines.
  899. BasePlatformAdapter override
  900. """
  901. if not content:
  902. return content
  903. normalised = content.replace("\r\n", "\n").replace("\r", "\n")
  904. while "\n\n\n\n" in normalised:
  905. normalised = normalised.replace("\n\n\n\n", "\n\n\n")
  906. return normalised
  907. async def edit_message(
  908. self,
  909. chat_id: str,
  910. message_id: str,
  911. content: str,
  912. *,
  913. finalize: bool = False,
  914. ) -> SendResult:
  915. """Edit a message we previously sent, via MessageService/UpdateMessage.
  916. The stream consumer drives streaming replies through this: without the
  917. override the base class reports "Not supported" and every incremental
  918. update arrives as a *new* message.
  919. ``finalize`` is a no-op for Chatto — an edit is an edit here, there is
  920. no in-progress card state to close out (hence no
  921. ``REQUIRES_EDIT_FINALIZE``).
  922. Content that exceeds the per-message limit is refused rather than
  923. silently truncated, so the caller falls back to ``send()``, which
  924. splits across messages.
  925. BasePlatformAdapter override
  926. """
  927. if not message_id:
  928. return SendResult(success=False, error="Chatto: no message id to edit")
  929. if not content:
  930. return SendResult(success=False, error="Empty message")
  931. formatted = self.format_message(content)
  932. if len(formatted) > ChattoConstants.MAX_MESSAGE_LENGTH:
  933. # Refuse instead of truncating: the caller's fallback path splits.
  934. return SendResult(
  935. success=False,
  936. error=(
  937. f"Chatto: edit exceeds {ChattoConstants.MAX_MESSAGE_LENGTH} "
  938. f"chars ({len(formatted)})"
  939. ),
  940. )
  941. try:
  942. client = await self._require_client()
  943. except RuntimeError:
  944. return SendResult(success=False, error="Chatto client not available", retryable=True)
  945. try:
  946. msg = await client.update_message(
  947. room_id=str(chat_id),
  948. event_id=str(message_id),
  949. body=formatted,
  950. )
  951. except ChattoError as e:
  952. logger.warning("Chatto: UpdateMessage failed for %s: %s", message_id, e)
  953. return SendResult(success=False, error=str(e), retryable=True)
  954. except Exception as e:
  955. logger.warning("Chatto: UpdateMessage error for %s: %s", message_id, e)
  956. return SendResult(success=False, error=str(e), retryable=False)
  957. # Our own edit comes back as a message_edited event; mark it seen so it
  958. # is never mistaken for inbound traffic.
  959. edited_id = getattr(msg, "id", "") or str(message_id)
  960. self._mark_seen(edited_id)
  961. return SendResult(success=True, message_id=edited_id, raw_response=msg)
  962. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  963. """Delete a message via MessageService/DeleteMessage.
  964. Used by the stream consumer's fresh-final cleanup (removing a preview
  965. message once the completed reply has been sent) and by the ephemeral
  966. reply TTL.
  967. BasePlatformAdapter override
  968. """
  969. if not chat_id or not message_id:
  970. return False
  971. try:
  972. client = await self._require_client()
  973. except RuntimeError:
  974. logger.warning("Chatto: DeleteMessage — client unavailable")
  975. return False
  976. try:
  977. return bool(await client.delete_message(
  978. room_id=str(chat_id), event_id=str(message_id),
  979. ))
  980. except ChattoError as e:
  981. logger.warning("Chatto: DeleteMessage failed for %s: %s", message_id, e)
  982. return False
  983. except Exception as e:
  984. logger.warning("Chatto: DeleteMessage error for %s: %s", message_id, e)
  985. return False
  986. async def create_handoff_thread(
  987. self, parent_chat_id: str, name: str,
  988. ) -> Optional[str]:
  989. """Anchor a session handoff in a fresh thread under *parent_chat_id*.
  990. Chatto threads hang off a message, not off the room, so we post a seed
  991. message and hand its ID back as the thread root — the same shape the
  992. Slack adapter uses. DMs don't support threads, so they get ``None``
  993. and the watcher keeps delivering into the DM itself.
  994. BasePlatformAdapter override
  995. """
  996. if not parent_chat_id:
  997. return None
  998. if self._room_kinds.get(parent_chat_id) == RoomKind.DM:
  999. logger.debug("Chatto: handoff thread skipped — %s is a DM", parent_chat_id)
  1000. return None
  1001. try:
  1002. client = await self._require_client()
  1003. except RuntimeError:
  1004. logger.warning("Chatto: handoff thread — client unavailable")
  1005. return None
  1006. seed_text = f"🧵 Hermes handoff — **{(name or 'session').strip()[:80]}**"
  1007. try:
  1008. msg = await client.post_message(room_id=str(parent_chat_id), body=seed_text)
  1009. except Exception as e:
  1010. logger.warning(
  1011. "Chatto: handoff thread seed-post failed for room %s: %s",
  1012. parent_chat_id, e,
  1013. )
  1014. return None
  1015. seed_id = getattr(msg, "id", "") or ""
  1016. if not seed_id:
  1017. logger.warning("Chatto: handoff thread seed-post returned no message id")
  1018. return None
  1019. self._mark_seen(seed_id)
  1020. self._our_message_ids.add(seed_id)
  1021. self._our_thread_roots.add(seed_id)
  1022. try:
  1023. await client.follow_thread(str(parent_chat_id), seed_id)
  1024. except Exception:
  1025. logger.debug(
  1026. "Chatto: follow_thread failed for handoff %s/%s",
  1027. parent_chat_id, seed_id, exc_info=True,
  1028. )
  1029. return seed_id
  1030. # Overridden from BaseAdapter:
  1031. async def send_typing(self, chat_id: str, metadata=None) -> None:
  1032. """Start a persistent typing indicator for a room.
  1033. Sends a typing ping every 10 seconds (Chatto's indicator likely
  1034. lasts ~8-10s). The background loop runs until ``stop_typing()``
  1035. is called or the task is cancelled.
  1036. BasePlatformAdapter override
  1037. """
  1038. if chat_id in self._typing_tasks:
  1039. return # already running
  1040. async def _typing_loop() -> None:
  1041. try:
  1042. while True:
  1043. try:
  1044. try:
  1045. client = await self._require_client()
  1046. except RuntimeError:
  1047. return
  1048. await client.update_typing_indicator(room_id=str(chat_id))
  1049. except asyncio.CancelledError:
  1050. return
  1051. except Exception:
  1052. pass
  1053. await asyncio.sleep(10)
  1054. except asyncio.CancelledError:
  1055. pass
  1056. finally:
  1057. self._typing_tasks.pop(chat_id, None)
  1058. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  1059. async def stop_typing(self, chat_id: str) -> None:
  1060. """Stop the persistent typing indicator for a room.
  1061. BasePlatformAdapter override
  1062. """
  1063. task = self._typing_tasks.pop(chat_id, None)
  1064. if task:
  1065. task.cancel()
  1066. try:
  1067. await task
  1068. except (asyncio.CancelledError, Exception):
  1069. pass
  1070. async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
  1071. """Get information about a chat/room.
  1072. BasePlatformAdapter override
  1073. """
  1074. name = self._room_names.get(chat_id, chat_id)
  1075. kind = self._room_kinds.get(chat_id)
  1076. return {
  1077. "name": name,
  1078. "type": chat_type_for_room_kind(kind).value,
  1079. }
  1080. # ------------------------------------------------------------------ #
  1081. # Reactions
  1082. # ------------------------------------------------------------------ #
  1083. @staticmethod
  1084. def _emoji_to_shortcode(emoji: str) -> str:
  1085. """Convert a unicode emoji to a Chatto shortcode name.
  1086. If the emoji is already a shortcode (no unicode mapping found),
  1087. return it as-is.
  1088. """
  1089. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  1090. if shortcode:
  1091. return shortcode
  1092. # Already a shortcode like "thumbsup" — return as-is
  1093. return emoji
  1094. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  1095. """Add a reaction to a message via MessageService/AddReaction."""
  1096. shortcode = self._emoji_to_shortcode(emoji)
  1097. try:
  1098. try:
  1099. client = await self._require_client()
  1100. except RuntimeError:
  1101. logger.warning("Chatto: AddReaction — client unavailable")
  1102. return False
  1103. result = await client.add_reaction(
  1104. room_id=room_id,
  1105. message_event_id=message_id,
  1106. emoji=shortcode,
  1107. )
  1108. return result
  1109. except ChattoError as e:
  1110. logger.warning("Chatto: AddReaction failed: %s", e)
  1111. return False
  1112. except Exception as e:
  1113. logger.warning("Chatto: AddReaction error: %s", e)
  1114. return False
  1115. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  1116. """Remove a reaction from a message via MessageService/RemoveReaction."""
  1117. shortcode = self._emoji_to_shortcode(emoji)
  1118. try:
  1119. try:
  1120. client = await self._require_client()
  1121. except RuntimeError:
  1122. logger.warning("Chatto: RemoveReaction — client unavailable")
  1123. return False
  1124. result = await client.remove_reaction(
  1125. room_id=str(chat_id),
  1126. message_event_id=str(message_id),
  1127. emoji=shortcode,
  1128. )
  1129. return result
  1130. except ChattoError as e:
  1131. logger.warning("Chatto: RemoveReaction failed: %s", e)
  1132. return False
  1133. except Exception as e:
  1134. logger.warning("Chatto: RemoveReaction error: %s", e)
  1135. return False
  1136. # ------------------------------------------------------------------ #
  1137. # DM initiation (Chatto-unique)
  1138. # ------------------------------------------------------------------ #
  1139. async def start_dm(self, user_id: str) -> Optional[str]:
  1140. """Start a direct message with a user via RoomService/StartDM.
  1141. Returns the room ID on success, or None on failure.
  1142. """
  1143. if not user_id:
  1144. return None
  1145. try:
  1146. try:
  1147. client = await self._require_client()
  1148. except RuntimeError:
  1149. return None
  1150. room = await client.start_dm(participant_ids=[str(user_id)])
  1151. self._room_names[room.id] = room.name
  1152. self._room_kinds[room.id] = room.kind
  1153. return room.id
  1154. except ChattoError as e:
  1155. logger.debug("Chatto: StartDM failed: %s", e)
  1156. return None
  1157. except Exception as e:
  1158. logger.debug("Chatto: StartDM error: %s", e)
  1159. return None
  1160. # ------------------------------------------------------------------ #
  1161. # Room creation (Chatto-unique)
  1162. # ------------------------------------------------------------------ #
  1163. async def create_room(
  1164. self,
  1165. name: str,
  1166. description: str = "",
  1167. group_id: str = "",
  1168. universal: bool = True,
  1169. ) -> Optional[str]:
  1170. """Create an ad-hoc room via RoomService/CreateRoom.
  1171. Returns the room ID on success, or None on failure.
  1172. """
  1173. try:
  1174. try:
  1175. client = await self._require_client()
  1176. except RuntimeError:
  1177. return None
  1178. room = await client.create_room(
  1179. name=name,
  1180. group_id=group_id or "",
  1181. description=description,
  1182. universal=universal,
  1183. )
  1184. rid = str(room.id) if room else ""
  1185. if rid:
  1186. self._room_names[rid] = room.name
  1187. self._room_kinds[rid] = room.kind
  1188. return rid
  1189. logger.debug("Chatto: CreateRoom returned no room id")
  1190. return None
  1191. except ChattoError as e:
  1192. logger.debug("Chatto: CreateRoom failed: %s", e)
  1193. return None
  1194. except Exception as e:
  1195. logger.debug("Chatto: CreateRoom error: %s", e)
  1196. return None
  1197. # ------------------------------------------------------------------ #
  1198. # Processing lifecycle hooks (reactions-based, like Discord)
  1199. # ------------------------------------------------------------------ #
  1200. def _event_room_and_message_id(self, event: MessageEvent) -> Tuple[str, str]:
  1201. """Extract room_id and message_id from a MessageEvent."""
  1202. message_id = event.message_id or ""
  1203. chat_id = event.source.chat_id
  1204. return chat_id, message_id
  1205. async def on_processing_start(self, event: MessageEvent) -> None:
  1206. """Add an 👀 (eyes) reaction to the incoming message.
  1207. BasePlatformAdapter override
  1208. """
  1209. logger.info("self.chatto_config.reactions.value: %s", self.chatto_config.reactions.value)
  1210. if not self.chatto_config.reactions.value:
  1211. return
  1212. chat_id, message_id = self._event_room_and_message_id(event)
  1213. if not chat_id or not message_id:
  1214. logger.warning("Chatto: on_processing_start — empty chat_id or message_id, skipping reaction")
  1215. return
  1216. await self.add_reaction(chat_id, message_id, "👀")
  1217. async def on_processing_complete(
  1218. self, event: MessageEvent, outcome: ProcessingOutcome
  1219. ) -> None:
  1220. """Swap the 👀 reaction for ✅ (success) or ❌ (failure).
  1221. BasePlatformAdapter override
  1222. """
  1223. if not self.chatto_config.reactions.value:
  1224. return
  1225. chat_id, message_id = self._event_room_and_message_id(event)
  1226. if not chat_id or not message_id:
  1227. return
  1228. # Remove the processing eyes reaction
  1229. await self.remove_reaction(chat_id, message_id, "👀")
  1230. # Add the outcome reaction
  1231. if outcome == ProcessingOutcome.SUCCESS:
  1232. await self.add_reaction(chat_id, message_id, "✅")
  1233. elif outcome == ProcessingOutcome.FAILURE:
  1234. await self.add_reaction(chat_id, message_id, "❌")
  1235. # ------------------------------------------------------------------ #
  1236. # Asset upload (chunked)
  1237. # ------------------------------------------------------------------ #
  1238. async def _upload_asset(self, room_id: str, file_path: str) -> Optional[str]:
  1239. """Upload a file via the chunked AssetUploadService.
  1240. Returns the asset ID on success, or None on failure.
  1241. """
  1242. try:
  1243. with open(file_path, "rb") as f:
  1244. file_data = f.read()
  1245. except Exception as e:
  1246. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  1247. return None
  1248. if not file_data:
  1249. logger.error("Chatto: file %s is empty", file_path)
  1250. return None
  1251. file_size = len(file_data)
  1252. file_name = os.path.basename(file_path)
  1253. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  1254. sha256_hash = hashlib.sha256(file_data).hexdigest()
  1255. try:
  1256. try:
  1257. client = await self._require_client()
  1258. except RuntimeError:
  1259. logger.error("Chatto: upload aborted - no client available")
  1260. return None
  1261. # Step 1: Create upload session
  1262. upload = await client.create_upload(
  1263. room_id=room_id,
  1264. filename=file_name,
  1265. size=file_size,
  1266. sha256=sha256_hash,
  1267. content_type=mime_type,
  1268. )
  1269. upload_id = str(getattr(cast(Any, upload), "id", ""))
  1270. if not upload_id:
  1271. logger.error("Chatto: CreateUpload returned no upload ID")
  1272. return None
  1273. # Step 2: Upload chunks
  1274. offset = 0
  1275. while offset < file_size:
  1276. chunk = file_data[offset:offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  1277. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  1278. await client.upload_chunk(
  1279. upload_id=upload_id,
  1280. offset=offset,
  1281. content=chunk,
  1282. chunk_sha256=chunk_sha256,
  1283. )
  1284. offset += len(chunk)
  1285. # Step 3: Complete upload
  1286. upload, asset = await client.complete_upload(upload_id=upload_id)
  1287. if not asset:
  1288. logger.error("Chatto: CompleteUpload returned no asset")
  1289. return None
  1290. asset_id = str(getattr(cast(Any, asset), "id", ""))
  1291. logger.info("Chatto: uploaded %s as asset %s (%d bytes)", file_name, asset_id, file_size)
  1292. return asset_id
  1293. except ChattoError as e:
  1294. logger.error("Chatto: upload failed: %s", e)
  1295. return None
  1296. except Exception as e:
  1297. logger.error("Chatto: upload error: %s", e)
  1298. return None
  1299. async def _post_attachment_message(
  1300. self,
  1301. chat_id: str,
  1302. asset_ids: List[str],
  1303. caption: Optional[str],
  1304. reply_to: Optional[str],
  1305. metadata: Optional[Dict[str, Any]],
  1306. ) -> SendResult:
  1307. """Post one message carrying already-uploaded assets."""
  1308. thread_id = (metadata or {}).get("thread_id")
  1309. if reply_to:
  1310. thread_id = reply_to
  1311. try:
  1312. try:
  1313. client = await self._require_client()
  1314. except RuntimeError:
  1315. return SendResult(success=False, error="Chatto client not available", retryable=True)
  1316. msg = await client.post_message(
  1317. room_id=str(chat_id),
  1318. body=self.format_message(caption) if caption else "",
  1319. attachment_asset_ids=asset_ids,
  1320. thread_root_event_id=str(thread_id) if thread_id else "",
  1321. )
  1322. self._mark_seen(msg.id)
  1323. self._our_message_ids.add(msg.id)
  1324. return SendResult(success=True, message_id=msg.id, raw_response=msg)
  1325. except ChattoError as e:
  1326. return SendResult(success=False, error=str(e), retryable=True)
  1327. except Exception as e:
  1328. return SendResult(success=False, error=str(e), retryable=False)
  1329. async def _send_local_attachment(
  1330. self,
  1331. chat_id: str,
  1332. file_path: str,
  1333. caption: Optional[str],
  1334. reply_to: Optional[str],
  1335. metadata: Optional[Dict[str, Any]],
  1336. *,
  1337. kind: str,
  1338. ) -> SendResult:
  1339. """Upload a local file and post it as a native Chatto attachment.
  1340. Shared by ``send_image_file``/``send_document``/``send_video``/
  1341. ``send_voice`` — the upload mechanics are identical, only the wording of
  1342. the failure notice differs. On failure we send that notice as text and
  1343. never the host path (it leaks the Hermes home layout).
  1344. """
  1345. notice = f"⚠️ Couldn't deliver the {kind} attachment."
  1346. safe_path = self.validate_media_delivery_path(file_path)
  1347. if not safe_path:
  1348. logger.warning(
  1349. "[%s] send %s: unsafe path %s", self.name, kind, file_path,
  1350. )
  1351. text = f"{caption}\n{notice}" if caption else notice
  1352. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1353. asset_id = await self._upload_asset(str(chat_id), safe_path)
  1354. if not asset_id:
  1355. logger.warning(
  1356. "[%s] send %s: upload failed for %s", self.name, kind, safe_path,
  1357. )
  1358. text = f"{caption}\n{notice}" if caption else notice
  1359. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1360. return await self._post_attachment_message(
  1361. chat_id, [asset_id], caption, reply_to, metadata,
  1362. )
  1363. async def send_image_file(
  1364. self,
  1365. chat_id: str,
  1366. image_path: str,
  1367. caption: Optional[str] = None,
  1368. reply_to: Optional[str] = None,
  1369. metadata: Optional[Dict[str, Any]] = None,
  1370. **kwargs,
  1371. ) -> SendResult:
  1372. """Send a local image file via the chunked upload API.
  1373. The parameter is ``image_path``, not ``file_path``: every caller passes
  1374. it by keyword (``gateway/run.py:22354``, ``:22470``, and the base class's
  1375. own ``send_multiple_images`` file:// branch), so a renamed parameter
  1376. makes each of those raise TypeError and silently degrade to a text
  1377. notice.
  1378. BasePlatformAdapter override
  1379. """
  1380. return await self._send_local_attachment(
  1381. chat_id, image_path, caption, reply_to, metadata, kind="image",
  1382. )
  1383. async def send_document(
  1384. self,
  1385. chat_id: str,
  1386. file_path: str,
  1387. caption: Optional[str] = None,
  1388. file_name: Optional[str] = None,
  1389. reply_to: Optional[str] = None,
  1390. metadata: Optional[Dict[str, Any]] = None,
  1391. **kwargs,
  1392. ) -> SendResult:
  1393. """Send a local file as a native Chatto attachment.
  1394. ``file_name`` is the user-facing name the agent chose; Chatto takes the
  1395. filename from the upload session, so it only matters for the failure
  1396. notice.
  1397. BasePlatformAdapter override
  1398. """
  1399. result = await self._send_local_attachment(
  1400. chat_id, file_path, caption, reply_to, metadata, kind="file",
  1401. )
  1402. if not result.success and file_name:
  1403. logger.debug("Chatto: document delivery failed for %s", file_name)
  1404. return result
  1405. async def send_video(
  1406. self,
  1407. chat_id: str,
  1408. video_path: str,
  1409. caption: Optional[str] = None,
  1410. reply_to: Optional[str] = None,
  1411. metadata: Optional[Dict[str, Any]] = None,
  1412. **kwargs,
  1413. ) -> SendResult:
  1414. """Send a local video as a native Chatto attachment (Chatto transcodes
  1415. and plays it inline).
  1416. BasePlatformAdapter override
  1417. """
  1418. return await self._send_local_attachment(
  1419. chat_id, video_path, caption, reply_to, metadata, kind="video",
  1420. )
  1421. async def send_voice(
  1422. self,
  1423. chat_id: str,
  1424. audio_path: str,
  1425. caption: Optional[str] = None,
  1426. reply_to: Optional[str] = None,
  1427. metadata: Optional[Dict[str, Any]] = None,
  1428. **kwargs,
  1429. ) -> SendResult:
  1430. """Send a local audio file as a native Chatto attachment.
  1431. Chatto has no dedicated voice-bubble type, so this is an ordinary audio
  1432. attachment — still far better than the base class's text notice.
  1433. BasePlatformAdapter override
  1434. """
  1435. return await self._send_local_attachment(
  1436. chat_id, audio_path, caption, reply_to, metadata, kind="audio",
  1437. )
  1438. async def send_image(
  1439. self,
  1440. chat_id: str,
  1441. image_url: str,
  1442. caption: Optional[str] = None,
  1443. reply_to: Optional[str] = None,
  1444. metadata: Optional[Dict[str, Any]] = None,
  1445. ) -> SendResult:
  1446. """Send an image to a Chatto room.
  1447. Tries to download the image from the URL and upload it as a native
  1448. attachment. Falls back to sending the URL as a link (Chatto renders
  1449. link previews) if the download fails.
  1450. BasePlatformAdapter override
  1451. """
  1452. # Try downloading and uploading as attachment
  1453. try:
  1454. import tempfile
  1455. import urllib.request as _urllib_request
  1456. # Download to a temp file
  1457. parsed = urlsplit(image_url)
  1458. url_path = parsed.path
  1459. ext = os.path.splitext(url_path)[1] or ".png"
  1460. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1461. try:
  1462. os.close(tmp_fd)
  1463. req = _urllib_request.Request(image_url, headers={"User-Agent": "Hermes/1.0"})
  1464. try:
  1465. import ssl
  1466. ctx = ssl.create_default_context()
  1467. except Exception:
  1468. ctx = None
  1469. with _urllib_request.urlopen(req, timeout=ChattoConstants.HTTP_TIMEOUT, context=ctx) as resp:
  1470. with open(tmp_path, "wb") as f:
  1471. f.write(resp.read())
  1472. # Upload as attachment
  1473. result = await self.send_image_file(
  1474. chat_id, tmp_path, caption=caption,
  1475. reply_to=reply_to, metadata=metadata,
  1476. )
  1477. if result.success:
  1478. return result
  1479. finally:
  1480. try:
  1481. os.unlink(tmp_path)
  1482. except OSError:
  1483. pass
  1484. except Exception as e:
  1485. logger.debug("Chatto: send_image download/upload failed, falling back to link: %s", e)
  1486. # Fallback: send as link (Chatto renders link previews)
  1487. text = image_url
  1488. if caption:
  1489. text = f"{caption}\n{image_url}"
  1490. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  1491. async def _materialise_image(self, image_url: str) -> Tuple[Optional[str], bool]:
  1492. """Resolve one ``send_multiple_images`` entry to a local file path.
  1493. Accepts ``http(s)://`` URLs (downloaded to a temp file), ``file://``
  1494. URIs and bare paths. Returns ``(path, is_temp)`` — the caller unlinks
  1495. when ``is_temp``. ``(None, False)`` means the entry is unusable.
  1496. """
  1497. import tempfile
  1498. from urllib.parse import unquote as _unquote
  1499. if image_url.startswith(("http://", "https://")):
  1500. parsed = urlsplit(image_url)
  1501. ext = os.path.splitext(parsed.path)[1] or ".png"
  1502. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  1503. os.close(tmp_fd)
  1504. try:
  1505. data = await self._download_attachment_bytes(image_url)
  1506. with open(tmp_path, "wb") as f:
  1507. f.write(data)
  1508. except Exception as e:
  1509. logger.warning("Chatto: image download failed for %s: %s", image_url, e)
  1510. try:
  1511. os.unlink(tmp_path)
  1512. except OSError:
  1513. pass
  1514. return None, False
  1515. return tmp_path, True
  1516. local = image_url
  1517. if local.startswith("file://"):
  1518. local = _unquote(urlsplit(local).path)
  1519. return self.validate_media_delivery_path(local), False
  1520. async def send_multiple_images(
  1521. self,
  1522. chat_id: str,
  1523. images: List[Tuple[str, str]],
  1524. metadata: Optional[Dict[str, Any]] = None,
  1525. human_delay: float = 0.0,
  1526. ) -> None:
  1527. """Send a batch of images as ONE message with several attachments.
  1528. The base implementation posts each image separately; a Chatto message
  1529. carries a list of attachment assets, so a batch belongs in a single
  1530. message (and a single notification).
  1531. ``human_delay`` is ignored deliberately — there is only one outbound
  1532. call to pace. Entries that can't be fetched are dropped with a warning;
  1533. if nothing survives, we fall back to the base class so the user still
  1534. gets the links.
  1535. BasePlatformAdapter override
  1536. """
  1537. if len(images or []) < 2:
  1538. await super().send_multiple_images(
  1539. chat_id, images, metadata=metadata, human_delay=human_delay,
  1540. )
  1541. return
  1542. asset_ids: List[str] = []
  1543. captions: List[str] = []
  1544. for image_url, alt_text in images:
  1545. path, is_temp = await self._materialise_image(image_url)
  1546. if not path:
  1547. logger.warning("Chatto: skipping unusable image %s", image_url)
  1548. continue
  1549. try:
  1550. asset_id = await self._upload_asset(str(chat_id), path)
  1551. finally:
  1552. if is_temp:
  1553. try:
  1554. os.unlink(path)
  1555. except OSError:
  1556. pass
  1557. if not asset_id:
  1558. logger.warning("Chatto: upload failed for image %s", image_url)
  1559. continue
  1560. asset_ids.append(asset_id)
  1561. if alt_text:
  1562. captions.append(alt_text)
  1563. if not asset_ids:
  1564. logger.warning(
  1565. "Chatto: no image survived upload, falling back to per-image delivery",
  1566. )
  1567. await super().send_multiple_images(
  1568. chat_id, images, metadata=metadata, human_delay=human_delay,
  1569. )
  1570. return
  1571. if len(asset_ids) < len(images):
  1572. logger.warning(
  1573. "Chatto: sending %d of %d images — the rest could not be uploaded",
  1574. len(asset_ids), len(images),
  1575. )
  1576. await self._post_attachment_message(
  1577. chat_id, asset_ids, "\n".join(captions) or None, None, metadata,
  1578. )
  1579. # ---------------------------------------------------------------------------
  1580. # Cron / out-of-process delivery
  1581. # ---------------------------------------------------------------------------
  1582. async def hermes_standalone_sender_fn(
  1583. pconfig,
  1584. chat_id,
  1585. message,
  1586. *,
  1587. thread_id=None,
  1588. media_files=None,
  1589. force_document=False,
  1590. ) -> SendResult:
  1591. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  1592. Used by cron / scheduled routines that run out-of-process. Creates a
  1593. short-lived chattolib client, posts, and closes.
  1594. """
  1595. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  1596. # Create a temporary client for standalone sending — we need a base URL plus
  1597. # either a token or a full login/password pair.
  1598. has_credentials = bool(
  1599. chatto_config.token.value
  1600. or (chatto_config.login.value and chatto_config.password.value)
  1601. )
  1602. if not chatto_config.base_url.value or not has_credentials:
  1603. return SendResult(success=False, error="Chatto: base URL or credentials missing")
  1604. client: ChattoClient
  1605. try:
  1606. if chatto_config.token.value:
  1607. client = ChattoClient(base_url=chatto_config.base_url.value, token=chatto_config.token.value)
  1608. else:
  1609. client = await ChattoClient.login(
  1610. base_url=chatto_config.base_url.value,
  1611. login=chatto_config.login.value,
  1612. password=chatto_config.password.value,
  1613. )
  1614. except Exception as exc:
  1615. return SendResult(success=False, error=f"Chatto login failed: {exc}")
  1616. try:
  1617. kwargs: Dict[str, Any] = {}
  1618. if chatto_config.auto_thread.value and thread_id:
  1619. kwargs["in_reply_to"] = thread_id
  1620. if media_files and media_files.get("attachment_asset_ids"):
  1621. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  1622. try:
  1623. posted = await client.post_message(chat_id, message, **kwargs)
  1624. except Exception as exc:
  1625. return SendResult(success=False, error=str(exc))
  1626. return SendResult(success=True, message_id=getattr(posted, "id", "") or None)
  1627. finally:
  1628. try:
  1629. await client.close()
  1630. except Exception as exc:
  1631. logger.error(
  1632. "Chatto standalone: error closing short-lived client (perhaps already closed): %s", exc,
  1633. )
  1634. def hermes_validate_config(config: PlatformConfig) -> bool:
  1635. """"
  1636. Function name should be the same as register argument name with "hermes_" prefix, so we
  1637. know that it is needed for plugin register(). Do not change signature.
  1638. - config
  1639. Check whether Chatto Plugin is configured. Compare to hermes_is_connected()."""
  1640. chatto_config = ChattoConfiguration(pconfig=config)
  1641. if len(chatto_config.allowed_users.value) > 0 and chatto_config.allow_all_users.value:
  1642. logger.info("Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both.")
  1643. return False
  1644. if chatto_config.base_url.value:
  1645. if (chatto_config.token.value is not None) or (chatto_config.login.value and chatto_config.password.value):
  1646. return True
  1647. else:
  1648. logger.error("Chatto: Minimally, either token or login/password must be set.")
  1649. else:
  1650. logger.error("Chatto: base_url must be set.")
  1651. return False
  1652. def hermes_check_fn() -> bool:
  1653. """Check if Chatto is configured and dependencies are available.
  1654. Add real logic?! Or just .. there are no dependencies.. always return true. Really. Docs suck."""
  1655. try:
  1656. import chattolib.client # noqa: F401 — vendored dependency probe
  1657. return True
  1658. except ImportError:
  1659. return False
  1660. # ---------------------------------------------------------------------------
  1661. # is_connected probe
  1662. # ---------------------------------------------------------------------------
  1663. def hermes_is_connected(config: PlatformConfig) -> bool:
  1664. """Check whether Chatto Plugin is connected. But where to? To the Hermes Agent? To Chatto Server?
  1665. The Hermes Agent plugin docs suck and it seems there are many functions to do the same."""
  1666. return bool(hermes_validate_config(config) and config.enabled)
  1667. def hermes_setup_fn() -> None:
  1668. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  1669. Function name should be the same as register argument name with "hermes_" prefix, so we
  1670. know that it is needed for plugin register().
  1671. """
  1672. from hermes_cli.setup import (
  1673. prompt,
  1674. prompt_yes_no,
  1675. save_env_value,
  1676. get_env_value,
  1677. print_header,
  1678. print_info,
  1679. print_warning,
  1680. print_success,
  1681. )
  1682. url = prompt(
  1683. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:")
  1684. if url:
  1685. save_env_value(ChattoConfiguration.base_url.env_name, url)
  1686. login = prompt("Chatto login (username):")
  1687. if login:
  1688. save_env_value(ChattoConfiguration.login.env_name, login)
  1689. password = prompt("Chatto password:", password=True)
  1690. if password:
  1691. save_env_value(ChattoConfiguration.password.env_name, password)
  1692. channels = prompt("Room IDs to watch (comma-separated, or empty for all):")
  1693. if channels:
  1694. save_env_value(ChattoConfiguration.channels_list.env_name, channels)
  1695. home = prompt("Home room ID for notifications (or empty):")
  1696. if home:
  1697. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  1698. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  1699. if allow_all:
  1700. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  1701. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  1702. def hermes_env_enablement_fn() -> Optional[dict]:
  1703. """Seed PlatformConfig.extra from env vars.
  1704. Returns a dict compatible with the PlatformConfig merge hook (or None
  1705. when no env-provided values are present).
  1706. Called by the platform registry during load_gateway_config().
  1707. Return None when the platform isn't minimally configured — the
  1708. caller then skips auto-enabling. Return a dict to seed extras.
  1709. The special 'home_channel' key is extracted and becomes a proper
  1710. HomeChannel dataclass on the PlatformConfig; every other key is
  1711. merged into PlatformConfig.extra.
  1712. Function name should be the same as register argument name with "hermes_" prefix, so we
  1713. know that it is needed for plugin register().
  1714. """
  1715. # Seed keys must be the config.yaml "extra" keys (config_key), NOT the env
  1716. # var names — ChattoConfiguration reads extra[config_key].
  1717. seed: Dict[str, Any] = {
  1718. ChattoConfiguration.base_url.config_key: (
  1719. os.getenv(ChattoConfiguration.base_url.env_name) or ChattoClient.DEFAULT_BASE_URL
  1720. ).strip(),
  1721. }
  1722. for field in ChattoConfiguration.fields():
  1723. if field.field_name == ChattoConfiguration.base_url.field_name:
  1724. continue
  1725. env_value = os.getenv(field.env_name)
  1726. if env_value:
  1727. seed[field.config_key] = env_value.strip()
  1728. logger.debug("seed: %s", {k: v for k, v in seed.items() if k not in ("token", "password")})
  1729. return seed
  1730. # ---------------------------------------------------------------------------
  1731. # Plugin registration entry point
  1732. # ---------------------------------------------------------------------------
  1733. def register(ctx) -> None:
  1734. """Plugin entry point — called by the Hermes plugin system."""
  1735. logger.info("Registering Chatto platform plugin on Hermes Agent")
  1736. logger.info("ChattoConfiguration.allowed_users.env_name: %s", ChattoConfiguration.allowed_users.env_name)
  1737. ctx.register_platform(
  1738. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  1739. label=ChattoConstants.PLATFORM_LABEL,
  1740. adapter_factory=hermes_adapter_factory,
  1741. check_fn=hermes_check_fn,
  1742. validate_config=hermes_validate_config,
  1743. is_connected=hermes_is_connected,
  1744. install_hint=ChattoConstants.INSTALL_HINT,
  1745. env_enablement_fn=hermes_env_enablement_fn,
  1746. setup_fn=hermes_setup_fn,
  1747. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  1748. standalone_sender_fn=hermes_standalone_sender_fn,
  1749. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  1750. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  1751. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  1752. emoji="💬",
  1753. allow_update_command=True,
  1754. pii_safe=False,
  1755. platform_hint=(
  1756. "You are chatting in Chatto (a self-hosted or cloud-hosted team or community chat server). "
  1757. "Markdown is supported. Users _may_ address you by @-mentioning your name. If configured, " \
  1758. "you also react without a @-mention. Direct messages reach you without a mention."
  1759. "Keep responses conversational."
  1760. ),
  1761. )