adapter.py 182 KB

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