adapter.py 189 KB

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