adapter.py 168 KB

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