adapter.py 212 KB

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