adapter.py 139 KB

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