adapter.py 217 KB

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