adapter.py 190 KB

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