adapter.py 87 KB

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