adapter.py 303 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504
  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 pathlib import Path
  34. from typing import Any, Final, NamedTuple, TypeVar
  35. from urllib.parse import unquote, urlsplit
  36. import httpx
  37. logger = logging.getLogger(__name__)
  38. from gateway.config import Platform, PlatformConfig
  39. from gateway.platforms.base import (
  40. BasePlatformAdapter,
  41. ExecApprovalPrompt,
  42. MessageEvent,
  43. MessageType,
  44. ProcessingOutcome,
  45. SendResult,
  46. cache_media_bytes,
  47. get_inbound_media_max_bytes,
  48. validate_inbound_media_size,
  49. )
  50. from gateway.session import SessionSource
  51. # Chattolib imports (vendored)
  52. # Using vendored chattolib from vendor/chattolib/
  53. # See vendor_chattolib.sh for how to update the vendored copy
  54. # Absolute imports — vendor/ is on sys.path (see above) and chattolib's own
  55. # modules import each other absolutely. Mixing in relative ".vendor.chattolib"
  56. # imports would load a second, distinct copy of every module, so isinstance()
  57. # checks across the two copies would silently fail.
  58. try:
  59. from chattolib._pb.chatto.api.v1.presence_pb2 import (
  60. PresenceStatus as ProtoPresenceStatus, # type: ignore[import-untyped]
  61. )
  62. from chattolib._pb.chatto.realtime.v1 import ( # noqa: F401 — importability probe
  63. realtime_pb2,
  64. )
  65. from chattolib._pb.chatto.realtime.v1.events_pb2 import (
  66. MessageMention, # type: ignore[import-untyped]
  67. MessagePostedEvent, # type: ignore[import-untyped]
  68. )
  69. from chattolib.client import (
  70. ChattoClient,
  71. )
  72. from chattolib.exceptions import (
  73. ChattoAuthError,
  74. ChattoConnectError,
  75. ChattoError,
  76. )
  77. from chattolib.realtime import (
  78. ChattoRealtimeCloseError,
  79. ChattoRealtimeError,
  80. RealtimeEvent,
  81. stream_events,
  82. )
  83. from chattolib.types import (
  84. Message,
  85. MessageAttachment,
  86. MessageSearchGroupBy,
  87. MessageSearchOrder,
  88. MessageSearchResult,
  89. MessageSearchScope,
  90. MessageSearchState,
  91. PresenceStatus,
  92. Room,
  93. RoomKind,
  94. RoomWithViewerState,
  95. User,
  96. format_datetime,
  97. )
  98. except ImportError as e:
  99. # Fail loudly: continuing here only defers the failure to a confusing
  100. # NameError somewhere deep in the adapter.
  101. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  102. raise
  103. try:
  104. from .platform_config import (
  105. ChattoConfiguration,
  106. ChattoConstants,
  107. )
  108. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  109. from platform_config import (
  110. ChattoConfiguration,
  111. ChattoConstants,
  112. )
  113. # --------------------------------------------------------------------------- #
  114. # Chat types
  115. # --------------------------------------------------------------------------- #
  116. class HermesChatType(StrEnum):
  117. """The ``chat_type`` vocabulary the Hermes gateway understands.
  118. Declared in ``gateway/session.py:161`` as ``"dm", "group", "channel",
  119. "thread"`` and consumed as a bare string all over the gateway:
  120. ``SessionSource.description`` (session.py:239) and the PII-redacting
  121. description in ``build_session_context_prompt`` (session.py:537) both
  122. branch on these exact values and fall back to a nameless generic case for
  123. anything else, and ``build_session_key`` puts the value straight into the
  124. session key. Passing a chattolib ``RoomKind`` (``"ROOM_KIND_CHANNEL"``)
  125. therefore does not fail loudly — it just quietly degrades what the agent is
  126. told about where it is.
  127. A StrEnum so it stays a drop-in ``str`` at every one of those call sites.
  128. GROUP vs CHANNEL
  129. ----------------
  130. There is no strict contract between the two, and the adapters disagree in
  131. practice: Slack labels every non-DM conversation ``"group"`` (including real
  132. channels), Discord uses both, and Telegram reserves ``"channel"`` for actual
  133. broadcast channels. The intended reading is ``group`` = ordinary
  134. multi-participant chat, ``channel`` = broadcast surface.
  135. The distinction only changes behaviour in three places:
  136. 1. Authorization (``gateway/authz_mixin.py``) — the only security-relevant
  137. one. The group-scoped env allowlists apply to ``{"group", "forum"}``
  138. ONLY, never to ``"channel"``: ``{PLATFORM}_GROUP_ALLOWED_USERS`` /
  139. ``_GROUP_ALLOWED_CHATS`` (:616), the chat-id allowlist (:708) and the
  140. Telegram legacy shim (:724). The adapter-delegation paths in turn treat
  141. all three alike (:461, :649, :674, :694), where the value only picks
  142. ``group_allow_from`` over ``allow_from`` from ``config.extra``.
  143. For Chatto both choices are equivalent today: those group env maps hold
  144. Telegram and QQBot only (:535-541), and our own allowlist runs through
  145. ``CHATTO_ALLOWED_USERS``, which is chat_type-independent.
  146. 2. What the agent is told — ``SessionSource.description`` renders
  147. ``"group: Name"`` vs ``"channel: Name"`` (session.py:239-246), likewise
  148. the PII-redacted variant (session.py:537-544).
  149. 3. The session key, which embeds the literal (session.py:1192). Changing
  150. the value for a room re-buckets its existing sessions.
  151. Explicitly NOT affected: ``is_shared_multi_user_session`` (session.py:1063)
  152. only looks at ``"dm"`` and ``thread_id``, so sender prefixes, the multi-user
  153. prompt line and ``group_sessions_per_user`` treat group and channel
  154. identically.
  155. """
  156. DM = "dm"
  157. GROUP = "group"
  158. CHANNEL = "channel"
  159. # Emitted by adapters whose thread events are their own chat type (Slack,
  160. # Discord). We don't: a Chatto thread keeps its room's chat_type and is
  161. # identified by ``thread_id`` on the source instead. Listed for the record,
  162. # because build_session_key rewrites the slot to "thread" itself
  163. # (session.py:1190).
  164. THREAD = "thread"
  165. # Not declared in session.py:161 but real: Telegram forum topics travel as
  166. # "forum", and the authz group allowlists above accept it alongside "group".
  167. # Chatto has no equivalent, so we never emit it.
  168. # Chatto only distinguishes DMs from channels. UNSPECIFIED means the server
  169. # sent a kind this vendored chattolib doesn't know: map it to the generic
  170. # multi-user bucket rather than guessing "channel", and never to "dm" — that
  171. # value drives session isolation (is_shared_multi_user_session, session.py:1063)
  172. # and would silently turn a room into a private conversation.
  173. #
  174. # CHANNEL for RoomKind.CHANNEL is the descriptive choice and carries no
  175. # behavioural cost (see the GROUP vs CHANNEL note above). Switching to GROUP for
  176. # Slack parity would be this one line — plus the re-bucketing of existing
  177. # sessions that point 3 of that note describes.
  178. _ROOM_KIND_TO_CHAT_TYPE: dict[RoomKind, HermesChatType] = {
  179. RoomKind.DM: HermesChatType.DM,
  180. RoomKind.CHANNEL: HermesChatType.CHANNEL,
  181. RoomKind.UNSPECIFIED: HermesChatType.GROUP,
  182. }
  183. def chat_type_for_room_kind(kind: RoomKind | None) -> HermesChatType:
  184. """Map a chattolib RoomKind onto the gateway's chat_type vocabulary.
  185. An unknown or missing kind becomes ``GROUP`` — see ``_ROOM_KIND_TO_CHAT_TYPE``.
  186. """
  187. if kind is None:
  188. return HermesChatType.GROUP
  189. return _ROOM_KIND_TO_CHAT_TYPE.get(kind, HermesChatType.GROUP)
  190. class RoomPolicy(StrEnum):
  191. """How a channel-kind room treats an inbound message.
  192. Derived per room from ``CHATTO_REQUIRE_MENTION_ROOMS`` /
  193. ``CHATTO_OPTIONAL_MENTION_ROOMS`` — see ``_room_policy``. A StrEnum
  194. so the values log readably without a formatting dance.
  195. """
  196. # Listed for unaddressed answers: every message is dispatched, and one
  197. # aimed at a named colleague gets a 🫥 acknowledgement instead of a reply.
  198. OPEN = "open"
  199. # Listed for addressed-only participation: dispatches only messages that
  200. # mention the bot (@name or a broadcast handle); others are dropped.
  201. REQUIRE_MENTION = "require_mention"
  202. # Listed in neither config: the room is silent — not dispatched at all,
  203. # read-only like any unlisted membership.
  204. SILENT = "silent"
  205. # Blocking filesystem/network helpers. The adapter runs on the shared gateway
  206. # event loop, so file reads and HTTP downloads are pushed to a worker thread
  207. # via asyncio.to_thread — a slow disk or dead image URL must not stall every
  208. # platform's message processing.
  209. def _read_file_bytes(path: str) -> bytes:
  210. """Read a whole file synchronously (run via asyncio.to_thread)."""
  211. with open(path, "rb") as f:
  212. return f.read()
  213. def _write_file_bytes(path: str, data: bytes) -> None:
  214. """Write bytes to a file synchronously (run via asyncio.to_thread)."""
  215. with open(path, "wb") as f:
  216. f.write(data)
  217. def _normalise_outbound_text(content: str) -> str:
  218. """Normalise outgoing text for Chatto.
  219. Chatto renders Markdown natively, so there is nothing to escape or
  220. translate — the only transformations here are the ones that measurably
  221. render wrong: CRLF line endings (which show up as stray blank lines)
  222. and runs of more than two blank lines. Shared by the adapter's
  223. ``format_message`` and the standalone cron sender, so both paths render
  224. identically.
  225. """
  226. if not content:
  227. return content
  228. normalised = content.replace("\r\n", "\n").replace("\r", "\n")
  229. while "\n\n\n\n" in normalised:
  230. normalised = normalised.replace("\n\n\n\n", "\n\n\n")
  231. return normalised
  232. def _oldest_first(messages: list[Message]) -> list[Message]:
  233. """Sort messages by the timestamp they carry, oldest first.
  234. The server's ordering is not a contract anything here builds on — it is a
  235. page, and a page's order depends on which end it was fetched from — so
  236. every timeline is read the way a conversation is spoken. A message with no
  237. timestamp sorts first: it is the one whose position we know least about,
  238. and putting it at the end would claim an order the data does not support.
  239. Shared by the thread seeding and the read tools so the block an agent reads
  240. in a session and the block it gets from ``chatto_get_history`` are ordered
  241. by one rule.
  242. """
  243. return sorted(
  244. messages, key=lambda m: m.created_at or datetime.min.replace(tzinfo=UTC)
  245. )
  246. # --------------------------------------------------------------------------- #
  247. # Adapter
  248. # --------------------------------------------------------------------------- #
  249. # Presence as the roster block spells it. UNSPECIFIED gets no label: a server
  250. # that never tracked presence should not have the roster claim anything.
  251. _PRESENCE_LABELS = {
  252. PresenceStatus.ONLINE: "online",
  253. PresenceStatus.AWAY: "away",
  254. PresenceStatus.DO_NOT_DISTURB: "do not disturb",
  255. PresenceStatus.OFFLINE: "offline",
  256. }
  257. # Proto enum name (``PRESENCE_STATUS_ONLINE``) → chattolib member, built once
  258. # from the enum's own values. The realtime wire carries the presence status as
  259. # a plain int (protobuf runtime without native enum wrappers), so every
  260. # presence change needs this lookup — a linear scan per event would be O(n) on
  261. # a hot path for a five-member enum.
  262. _PRESENCE_BY_PROTO_NAME = {member.value: member for member in PresenceStatus}
  263. @dataclass(frozen=True)
  264. class _Mentions:
  265. """Who one inbound message addresses.
  266. Both admission gates read this and nothing else, so "addressed" has a
  267. single definition. What fills it differs by path, not what counts:
  268. - :meth:`from_payload` reads the targets the server resolved when the
  269. message was posted. It is authoritative and the only source the posted
  270. path uses.
  271. - ``ChattoAdapter._mentions_from_body`` re-derives them from the text,
  272. because an edit event carries no targets — see
  273. ``_dispatch_message_edited``.
  274. Broadcast and role targets arrive unexpanded (one ``all``/``here``/``role``
  275. entry, never one per recipient), which is why the payload path needs no
  276. room roster to answer "was this meant for me".
  277. """
  278. me: bool = False
  279. someone_else: bool = False
  280. @classmethod
  281. def from_payload(
  282. cls, mentions: Iterable[MessageMention], my_user_id: str
  283. ) -> _Mentions:
  284. """Read the server-resolved targets of a ``message_posted`` event.
  285. ``includes_viewer`` is the server's own answer to "did this target
  286. include me", decided when the message was posted and unaffected by
  287. membership since. A direct target naming somebody else is the only
  288. kind that means "not for us": broadcasts and roles address the room,
  289. and we are in it.
  290. """
  291. me = False
  292. someone_else = False
  293. for mention in mentions:
  294. if mention.includes_viewer:
  295. me = True
  296. elif mention.WhichOneof("cause") == "direct" and (
  297. mention.direct.user_id != my_user_id
  298. ):
  299. someone_else = True
  300. return cls(me=me, someone_else=someone_else)
  301. @dataclass
  302. class _RoomRoster:
  303. """One announced room's roster projection.
  304. A miniature of the server's room membership: which user IDs belong to
  305. the room (the users themselves live in the shared ``_user_cache``) and
  306. how many directory entries were beyond the fetch limit, rendered as
  307. ``… and N more``. Presence changes patch the cached users in place;
  308. only a membership change or reconnect discards this and refetches.
  309. """
  310. member_ids: set[str] = field(default_factory=set)
  311. unfetched: int = 0
  312. @dataclass
  313. class _ClarifyPrompt:
  314. """State for a reaction-driven clarify prompt posted to a Chatto room."""
  315. clarify_id: str
  316. choices: list[str]
  317. session_key: str
  318. chat_id: str
  319. message_id: str
  320. resolved: bool = False
  321. awaiting_text: bool = False
  322. resolved_by: str | None = None
  323. resolved_choice: str | None = None
  324. expires_at: float = 0.0
  325. @dataclass
  326. class _ApprovalPrompt:
  327. """State for a reaction-driven exec-approval prompt posted to a Chatto room."""
  328. session_key: str
  329. chat_id: str
  330. message_id: str
  331. choices_map: dict[str, str] # emoji -> choice
  332. resolved: bool = False
  333. resolved_by: str | None = None
  334. resolved_choice: str | None = None
  335. expires_at: float = 0.0
  336. INTERACTIVE_PROMPT_TIMEOUT_SECONDS = 300
  337. # Check-mark variants that Chatto clients send for "the green check". The
  338. # prompts seed ✅ (U+2705), but emoji pickers offer near-identical glyphs with
  339. # a different codepoint — ✔️ adds a variation selector, ✓ is the plain text
  340. # check — and a client may also append or strip U+FE0F in transit. Matching
  341. # only the seeded form rejected the very reaction the prompt asks for.
  342. _CHECK_EMOJI_ALIASES: Final[frozenset[str]] = frozenset(
  343. {"\u2705", "\u2714", "\u2713", "\u2611", "\u221a"}
  344. )
  345. def _normalize_reaction_emoji(emoji: str) -> str:
  346. """The comparison key for a reaction emoji.
  347. Callers pass a decoded display emoji — shortcode names are translated by
  348. ``_SHORTCODE_TO_PROMPT_EMOJI`` first (see ``_try_handle_interactive_reaction``).
  349. Strips variation selectors (U+FE0E/U+FE0F) so ✔️ and ✔ collapse, then
  350. folds check-mark variants onto ✅. Keycap sequences (1️⃣ = digit + VS16 +
  351. combining keycap) lose only the VS16 — digit and U+20E3 survive, and seed
  352. and incoming reaction normalize to the same key.
  353. """
  354. stripped = emoji.replace("\ufe0e", "").replace("\ufe0f", "")
  355. return "✅" if stripped in _CHECK_EMOJI_ALIASES else stripped
  356. # Shortcodes the Chatto server accepts for AddReaction — its API takes gemoji
  357. # names ("white_check_mark"), never Unicode, and rejects anything else with
  358. # `invalid_argument: unsupported emoji`. The realtime events echo the same
  359. # names back, so incoming reactions arrive as shortcodes too. Reactions sent
  360. # as Unicode were silently dropped server-side; the cards then showed no
  361. # reaction anchors and every matching reaction answered "not a valid option".
  362. _PROMPT_SHORTCODES: Final[dict[str, str]] = {
  363. "1️⃣": "one",
  364. "2️⃣": "two",
  365. "3️⃣": "three",
  366. "4️⃣": "four",
  367. "5️⃣": "five",
  368. "6️⃣": "six",
  369. "7️⃣": "seven",
  370. "8️⃣": "eight",
  371. "9️⃣": "nine",
  372. "✏️": "pencil2",
  373. "✏": "pencil2",
  374. "✅": "white_check_mark",
  375. "🌀": "cyclone",
  376. "♾️": "infinity",
  377. "♾": "infinity",
  378. "❌": "x",
  379. }
  380. def _shortcode_for_reaction_emoji(emoji: str) -> str:
  381. """The shortcode name a Chatto reaction must be sent as.
  382. Prompt emojis map explicitly; anything else falls through to the adapter's
  383. general shortcode table. An unknown emoji is sent as-is — the server
  384. rejects it with `unsupported emoji`, which the caller logs.
  385. """
  386. return _PROMPT_SHORTCODES.get(emoji) or ChattoConstants.EMOJI_TO_SHORTCODE.get(
  387. emoji, emoji
  388. )
  389. # Inverse of _PROMPT_SHORTCODES plus the check-mark aliases: the server's
  390. # realtime events carry shortcode names, and reaction matching compares the
  391. # display emojis the cards seed — so "white_check_mark" must read as ✅.
  392. _SHORTCODE_TO_PROMPT_EMOJI: Final[dict[str, str]] = {
  393. name: emoji for emoji, name in _PROMPT_SHORTCODES.items()
  394. }
  395. _SHORTCODE_TO_PROMPT_EMOJI["heavy_check_mark"] = "✅"
  396. _SHORTCODE_TO_PROMPT_EMOJI["ballot_box_with_check"] = "✅"
  397. # Reaction glyphs for the interactive prompt cards. The display forms keep
  398. # their variation selectors — they are what the card text and the seed
  399. # reactions show, and that is what should render as colour emoji. Reaction
  400. # *matching* never uses them directly: incoming emojis are normalized first
  401. # (_normalize_reaction_emoji), so every comparison happens against the
  402. # normalized *_KEY forms below.
  403. _PROMPT_NUMBER_EMOJIS: Final[tuple[str, ...]] = (
  404. "1️⃣",
  405. "2️⃣",
  406. "3️⃣",
  407. "4️⃣",
  408. "5️⃣",
  409. "6️⃣",
  410. "7️⃣",
  411. "8️⃣",
  412. "9️⃣",
  413. )
  414. _PROMPT_OTHER_EMOJI: Final = "✏️"
  415. _PROMPT_APPROVAL_EMOJIS: Final[dict[str, str]] = {
  416. "once": "✅",
  417. "session": "🌀",
  418. "always": "♾️",
  419. "deny": "❌",
  420. }
  421. _NUMBER_EMOJI_KEYS: Final[tuple[str, ...]] = tuple(
  422. _normalize_reaction_emoji(emoji) for emoji in _PROMPT_NUMBER_EMOJIS
  423. )
  424. _OTHER_EMOJI_KEY: Final = _normalize_reaction_emoji(_PROMPT_OTHER_EMOJI)
  425. _UNSEEDED: Final = object()
  426. """Sentinel: nothing is known yet about how far this thread's session reaches.
  427. The in-memory map starts every thread here. The session's own copy starts here
  428. too — a session carrying no cursor is one whose frontier cannot be established
  429. (see _thread_context_for), which is not the same as a thread this process has
  430. not seeded.
  431. """
  432. _CURSOR_META_KEY: Final = "chatto.thread_seed_cursor"
  433. """Session-metadata key holding the last message ID a thread's session reached.
  434. One opaque ID per thread, on the session the platform already owns: nothing of
  435. the thread's content is mirrored anywhere, and the value dies with the session.
  436. """
  437. _T = TypeVar("_T")
  438. def hermes_adapter_factory(config: PlatformConfig):
  439. """Construct a ChattoAdapter from a PlatformConfig."""
  440. return ChattoAdapter(config)
  441. class ChattoAdapter(BasePlatformAdapter):
  442. """Chatto platform adapter.
  443. Receives messages via WebSocket realtime, sends via ConnectRPC.
  444. """
  445. # Read by BasePlatformAdapter.max_message_length_for_chat(), which the
  446. # gateway and the stream consumer use to chunk outgoing messages. Without
  447. # it they fall back to 4096 and split Chatto messages far earlier than
  448. # necessary — send() itself already truncates at SPLIT_THRESHOLD.
  449. MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  450. splits_long_messages = True
  451. supports_code_blocks: bool = True
  452. supports_status_text: bool = True # client.update_custom_status
  453. def __init__(self, pconfig: PlatformConfig):
  454. """Signature needs to be compatible with BasePlatformAdapter.__init__."""
  455. super().__init__(
  456. config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME)
  457. )
  458. # "extra" has been pre-populated by Hermes from config.yaml's extra block.
  459. # --- Configuration from our configuration data class with some logic ---
  460. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  461. # ------ State -------
  462. # Our own user, filled in by connect(). Events arriving before connect()
  463. # completes must not blow up on an undefined attribute.
  464. self.me: User | None = None
  465. # --- Runtime state ---
  466. self._room_names: dict[str, str] = {}
  467. self._room_kinds: dict[str, RoomKind] = {}
  468. # Last realtime cursor whose event was fully applied. Passed back to
  469. # stream_events on reconnect so the server resumes after it instead of
  470. # starting at the current boundary and silently skipping everything
  471. # that arrived while we were disconnected. None until the first event
  472. # carries one (chattolib leaves it unset for unreplayable events).
  473. self._realtime_cursor: str | None = None
  474. # Event IDs already processed — chattolib may redeliver events across
  475. # reconnects, so every inbound event is checked against this list.
  476. # Bounded deques: appending past the cap drops the oldest ID on its own.
  477. self._seen: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  478. # Message IDs this adapter has handed to the gateway (posted or
  479. # edit-re-dispatched). Edits of anything on this list never start a
  480. # fresh turn — that is the lock against re-answering settled
  481. # conversations by editing old messages.
  482. self._dispatched_ids: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  483. # Rooms whose member roster has been projected from the directory —
  484. # the roster is room-scoped and rides on every channel turn (threads
  485. # hold isolated sessions, so each turn needs its own copy). Together
  486. # with _rosters this is our miniature projection of server state:
  487. # presence changes patch the cached users in place; membership events
  488. # and reconnects discard a room so its next turn refetches once.
  489. self._roster_announced: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  490. # Announced rooms' membership projection (see _RoomRoster).
  491. self._rosters: dict[str, _RoomRoster] = {}
  492. # Thread roots whose history has been handed to their session, mapped to
  493. # the last message ID that was delivered. Thread sessions start empty, so
  494. # the first turn into a thread seeds what came before it — a cron message
  495. # whose echo we filtered as a self-event, or chatter that predates the
  496. # bot joining.
  497. #
  498. # The cursor is what makes later turns safe to seed again: the agent's
  499. # own messages never reach a session (their echo is filtered as a
  500. # self-event), so a reply it posts into a live thread via
  501. # chatto_send_room is invisible to that thread forever unless the tail
  502. # after the cursor is delivered. Re-delivering everything instead would
  503. # duplicate context on every turn. Insertion-ordered and capped like the
  504. # seen-ring; unlike the roster this is deliberately NOT discarded on
  505. # reconnect, since thread history is immutable.
  506. #
  507. # Keyed by thread root, which assumes one session per thread. With
  508. # thread_sessions_per_user turned on, each participant gets their own
  509. # session while this map stays shared, so one participant's turn moves
  510. # the cursor past the other's messages and that session is seeded once
  511. # and never again. The flag is off by default and this is the price of
  512. # switching it on; keying the map by session key would fix it.
  513. self._seeded_threads: dict[str, str] = {}
  514. # Threads whose cursor is on its way to the session but has not landed:
  515. # a thread's first turn has no session yet, and the second turn retries.
  516. self._unpersisted_threads: set[str] = set()
  517. # session_key -> message ID currently being processed there. Written
  518. # by on_processing_start, cleared by on_processing_complete; an edit
  519. # landing on the recorded ID is a mid-run correction.
  520. self._processing: dict[str, str] = {}
  521. self._joined_room_ids: list[str] = []
  522. # Rooms the server force-joined everyone into (Room.universal) — used
  523. # only for [universal] tags in the joined-rooms log line, never for
  524. # gating.
  525. self._universal_room_ids: set[str] = set()
  526. # DM room ID -> chat partner's login, resolved once via the member
  527. # directory so the joined-rooms summary can name who a DM is with.
  528. self._dm_partners: dict[str, str] = {}
  529. # One-shot guard for the unjoined-home-channel warning in _refresh_rooms.
  530. self._home_warning_logged = False
  531. self._ws_task: asyncio.Task | None = None
  532. self._presence_task: asyncio.Task | None = None
  533. # Persistent typing indicator loops per room
  534. self._typing_tasks: dict[str, asyncio.Task] = {}
  535. # Member directory cache: user_id -> user info dict
  536. self._user_cache: dict[str, User] = {}
  537. # Interactive prompt registries (clarify + exec-approval), keyed by
  538. # message_id. Reverse lookup _clarify_id_to_message supports
  539. # retire_clarify_card.
  540. self._clarify_prompts: dict[str, _ClarifyPrompt] = {}
  541. self._approval_prompts: dict[str, _ApprovalPrompt] = {}
  542. self._clarify_id_to_message: dict[str, str] = {}
  543. # Chattolib client cache and lock for async access.
  544. self._chatto_client: ChattoClient | None = None
  545. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  546. # ------------------------------------------------------------------ #
  547. # Auth
  548. # ------------------------------------------------------------------ #
  549. async def _get_chatto_client(self: ChattoAdapter) -> ChattoClient | None:
  550. """Return the shared ChattoClient, creating and logging in on first use.
  551. The default way to get a client. The fast path is a plain attribute
  552. read; first creation runs under a lock so concurrent callers log in
  553. exactly once. Returns ``None`` when no client exists yet or creation
  554. failed (bad credentials, unreachable server) — a normal state during
  555. startup, shutdown and reconnects, not an exceptional one. Callers
  556. decide what "no client" means for them, as a guard clause:
  557. client = await self._get_chatto_client()
  558. if client is None:
  559. logger.warning("Chatto: dropping X - no client available")
  560. return
  561. """
  562. if self._chatto_client is not None:
  563. return self._chatto_client
  564. async with self._chatto_client_lock:
  565. if self._chatto_client is not None:
  566. return self._chatto_client
  567. try:
  568. client = await self._open_client(
  569. base_url=self.chatto_config.base_url.value,
  570. token=self.chatto_config.token.value,
  571. )
  572. self._chatto_client = client
  573. logger.info(
  574. "Chatto: authenticated via token to '%s'",
  575. self.chatto_config.base_url.value,
  576. )
  577. return client
  578. except ChattoAuthError as e:
  579. logger.error("Chatto: authentication failed: %s", e)
  580. return None
  581. except (ChattoError, ValueError) as e:
  582. logger.error("Chatto: failed to create client: %s", e)
  583. return None
  584. async def _require_chatto_client(self) -> ChattoClient:
  585. """Return a ChattoClient or raise RuntimeError if unavailable.
  586. The exception-flavoured variant of :meth:`_get_chatto_client`, for
  587. callers whose surrounding machinery already routes exceptions.
  588. Currently that is only the realtime event loop, whose except chain
  589. turns the raise into a logged warning plus a backed-off reconnect —
  590. no special "no client" branch needed there. Everywhere else, prefer
  591. the ``is None`` guard shown in :meth:`_get_chatto_client`.
  592. """
  593. client = await self._get_chatto_client()
  594. if client is None:
  595. raise RuntimeError("Chatto client unavailable")
  596. return client
  597. # ------------------------------------------------------------------ #
  598. # Connection
  599. # ------------------------------------------------------------------ #
  600. async def _open_client(
  601. self,
  602. *,
  603. base_url: str,
  604. token: str | None = None,
  605. ) -> ChattoClient:
  606. """Return a connected ``ChattoClient`` using a bearer token.
  607. Raises ValueError when no token is configured — caught upstream as a
  608. normal creation failure, so misconfiguration reads as a logged error
  609. instead of a crash.
  610. """
  611. if not token:
  612. raise ValueError("Chatto: CHATTO_TOKEN not configured")
  613. return ChattoClient(token=token, base_url=base_url)
  614. async def connect(self, *, is_reconnect: bool = False) -> bool:
  615. """Connect to Chatto and start the realtime event stream.
  616. BasePlatformAdapter override
  617. """
  618. logger.info("Chatto: connecting...")
  619. client = await self._get_chatto_client()
  620. if client is None:
  621. self._set_fatal_error(
  622. "connect_failed", "Chatto client not available", retryable=True
  623. )
  624. return False
  625. # Get our first own user info
  626. try:
  627. self.me = await client.me()
  628. except Exception as exc:
  629. logger.error("Chatto: failed to get user info: %s", exc)
  630. self._set_fatal_error(
  631. "chatto_auth_failed",
  632. f"Chatto auth failed: {exc}",
  633. retryable=False,
  634. )
  635. try:
  636. if self._chatto_client is not None:
  637. await self._chatto_client.close()
  638. finally:
  639. self._chatto_client = None
  640. return False
  641. # Announce online presence so the bot appears online in the member list.
  642. # The server treats this as a TTL, so _presence_refresh_loop below has to
  643. # keep re-announcing it — a single call here lapses back to offline.
  644. await self._announce_online()
  645. self._closing = False
  646. # A cursor persisted by a clean shutdown lets this process pick up where
  647. # the previous one stopped, so a restart inside the window answers what
  648. # arrived while it was down instead of starting at the live boundary.
  649. self._realtime_cursor = _restore_realtime_cursor(self.chatto_config)
  650. if self._realtime_cursor:
  651. logger.info("Chatto: resuming the realtime stream from the stored cursor")
  652. # Start background realtime WS event stream loop.
  653. self._ws_task = asyncio.create_task(
  654. self._chattolib_event_loop(),
  655. name="chatto-event-stream",
  656. )
  657. self._presence_task = asyncio.create_task(
  658. self._presence_refresh_loop(),
  659. name="chatto-presence-refresh",
  660. )
  661. self._mark_connected()
  662. logger.info(
  663. "Chatto: connected to %s as '%s' (display_name: '%s' id: '%s')",
  664. self.chatto_config.base_url.value,
  665. self.me.login,
  666. self.me.display_name,
  667. self.me.id,
  668. )
  669. return True
  670. async def _announce_online(self) -> bool:
  671. """Tell the server we are online. Returns whether the call got through.
  672. Logged at warning level on failure: a silently dropped presence call is
  673. indistinguishable from a bot that is simply not running.
  674. """
  675. client = await self._get_chatto_client()
  676. if client is None:
  677. logger.warning(
  678. "Chatto: presence refresh failed, bot may appear offline: no client"
  679. )
  680. return False
  681. try:
  682. await client.set_presence(status=PresenceStatus.ONLINE)
  683. return True
  684. except Exception as exc:
  685. logger.warning(
  686. "Chatto: presence refresh failed, bot may appear offline: %s", exc
  687. )
  688. return False
  689. async def _presence_refresh_loop(self) -> None:
  690. """Re-announce ONLINE until disconnect, since presence expires server-side.
  691. Failures are not fatal — the next tick tries again, so a blip in the
  692. presence endpoint costs at most one interval of visible offline time.
  693. """
  694. while not self._closing:
  695. await self._sleep_interruptible(ChattoConstants.PRESENCE_REFRESH_INTERVAL)
  696. if self._closing:
  697. return
  698. await self._announce_online()
  699. async def disconnect(self) -> None:
  700. """Stop WebSocket, presence refresh, typing tasks, and clear state.
  701. BasePlatformAdapter override
  702. """
  703. # No explicit offline broadcast: chattolib rejects OFFLINE outright
  704. # ("stop refreshing to go offline"), so cancelling the refresh loop
  705. # below is what actually takes the bot offline.
  706. self._closing = True
  707. # Store the stream position before anything is torn down: this is the
  708. # one moment where a restart can resume instead of starting at the live
  709. # boundary, and it costs one small write.
  710. _persist_realtime_cursor(self.chatto_config, self._realtime_cursor)
  711. # Cancel all typing tasks
  712. for chat_id in list(self._typing_tasks.keys()):
  713. await self.stop_typing(chat_id)
  714. if self._ws_task and not self._ws_task.done():
  715. self._ws_task.cancel()
  716. try:
  717. await self._ws_task
  718. except (asyncio.CancelledError, Exception):
  719. logger.debug(
  720. "Chatto: websocket task ended during disconnect", exc_info=True
  721. )
  722. self._ws_task = None
  723. if self._presence_task and not self._presence_task.done():
  724. self._presence_task.cancel()
  725. try:
  726. await self._presence_task
  727. except (asyncio.CancelledError, Exception):
  728. logger.debug(
  729. "Chatto: presence task ended during disconnect", exc_info=True
  730. )
  731. self._presence_task = None
  732. if self._chatto_client:
  733. try:
  734. await self._chatto_client.close()
  735. except Exception:
  736. logger.exception("Chatto: error closing client")
  737. finally:
  738. self._chatto_client = None
  739. logger.info("Chatto: disconnected")
  740. self._mark_disconnected()
  741. async def _seed_room(self, room_id: str) -> None:
  742. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  743. try:
  744. client = await self._get_chatto_client()
  745. if client is None:
  746. logger.debug(
  747. "Chatto: _seed_room aborted - no client available for %s", room_id
  748. )
  749. return
  750. timeline_page = await client.get_room_events(room_id)
  751. for ev in timeline_page.events:
  752. if ev.id:
  753. self._mark_seen(ev.id)
  754. logger.debug(
  755. "Chatto: seeded room %s with %d events",
  756. room_id,
  757. len(timeline_page.events),
  758. )
  759. except Exception as e:
  760. logger.warning("Chatto: get room events failed for %s: %s", room_id, e)
  761. # ------------------------------------------------------------------ #
  762. # Realtime Event List
  763. # ------------------------------------------------------------------ #
  764. def _mark_seen(self, event_id: str) -> None:
  765. # The deque's maxlen evicts the oldest ID — no manual trimming.
  766. self._seen.append(event_id)
  767. def _is_seen(self, event_id: str) -> bool:
  768. return event_id in self._seen
  769. # ------------------------------------------------------------------ #
  770. # WebSocket Realtime Transport
  771. # ------------------------------------------------------------------ #
  772. def _own_handles(self) -> set[str]:
  773. """The handles that address this bot, lowercased for comparison.
  774. Chatto resolves mentions case-insensitively (FDR-006), so ``@Hermes_Bot``
  775. and ``@hermes_bot`` are the same handle everywhere in our gates.
  776. """
  777. if not self.me:
  778. return set()
  779. return {
  780. handle.lower() for handle in (self.me.login, self.me.display_name) if handle
  781. }
  782. def _mention_candidates(self, body: str) -> list[str]:
  783. """Candidate @-handles in a message body, in order of appearance.
  784. Mirrors the Chatto web frontend's extraction (apps/frontend/src/lib/
  785. mentions.ts upstream): candidates come from ``ChattoConstants.
  786. MENTION_RE`` outside code regions. Mentions inside fenced code blocks
  787. and inline code spans do not resolve upstream either, so a ``@bob``
  788. quoted in a snippet must not gate our behaviour.
  789. """
  790. without_fences = re.sub(r"(?s)(```|~~~).*?(\1|$)", " ", body)
  791. without_code = re.sub(r"`[^`\n]*`", " ", without_fences)
  792. return ChattoConstants.MENTION_RE.findall(without_code)
  793. def _mentions_from_body(self, body: str) -> _Mentions:
  794. """Re-derive the addressed parties from message text.
  795. Needed only for edited messages: an edit event carries no resolved
  796. targets, and re-gating on the new text is a promise we make on purpose
  797. (a mention added after posting still reaches the agent) — Chatto itself
  798. would not re-resolve, but it also has no turn for an edit to open. So
  799. this is the best available reading, not the authoritative one, and it
  800. inherits the regex's blind spots: a ``@bob`` inside a URL or blockquote
  801. reads as a mention here. The posted path does not have this problem —
  802. it reads the server's own resolution.
  803. Handles no user holds are not mentions: someone writing *about*
  804. mentioning ("per @-mention", "@nonexistent") is talking to us, and
  805. staying silent on a false positive is worse than answering one.
  806. """
  807. own = self._own_handles()
  808. me = False
  809. someone_else = False
  810. for handle in self._mention_candidates(body):
  811. lowered = handle.lower()
  812. if lowered in ChattoConstants.BROADCAST_MENTIONS or lowered in own:
  813. me = True
  814. elif self._handle_belongs_to_a_user(lowered):
  815. someone_else = True
  816. return _Mentions(me=me, someone_else=someone_else)
  817. def _handle_belongs_to_a_user(self, lowered_handle: str) -> bool:
  818. """Whether ``lowered_handle`` is the login of a real Chatto user.
  819. Resolved strictly from local knowledge — the member cache the adapter
  820. already keeps — never from the admin directory: ``admin_get_member``
  821. needs admin permissions a bot account must not be assumed to hold,
  822. and in the field its ``permission_denied`` failed every lookup, which
  823. fail-open let the bot answer every @colleague message. The cache is
  824. filled by the admission pipeline itself (room rosters are fetched for
  825. every channel turn), presence patching and the edited-message path.
  826. """
  827. return any(
  828. user is not None and (user.login or "").lower() == lowered_handle
  829. for user in self._user_cache.values()
  830. )
  831. def _check_auth(self, user: User) -> bool:
  832. """Whether this Chatto user may talk to the agent.
  833. Deliberately our own gate instead of the gateway's authz_mixin: its
  834. group allowlists key on chat_type and per-platform env vars
  835. (``{PLATFORM}_GROUP_ALLOWED_USERS``), none of which fit Chatto's one
  836. flat member directory. ``CHATTO_ALLOWED_USERS`` matches user IDs,
  837. ``CHATTO_ALLOW_ALL_USERS`` overrides it — the gate stays
  838. chat_type-independent by design.
  839. """
  840. if self._is_authorized(user.id):
  841. return True
  842. logger.warning(
  843. "Chatto: rejecting message from unauthorized user '%s' (%s)",
  844. user.login,
  845. user.id,
  846. )
  847. return False
  848. # ------------------------------------------------------------------ #
  849. # Room management over DM (/join, /leave)
  850. # ------------------------------------------------------------------ #
  851. _DM_COMMANDS = ("/join", "/leave")
  852. async def _handle_dm_command(self, room_id: str, body: str) -> bool:
  853. """Run a ``/join`` or ``/leave`` admin command sent as a direct message.
  854. Returns True when ``body`` is one of the commands — whether it
  855. succeeded or not — so the caller keeps it out of the agent pipeline.
  856. Membership lives on the Chatto server: a joined room reappears in
  857. every future ``list_rooms()`` and therefore survives restarts.
  858. """
  859. verb, _, argument = body.strip().partition(" ")
  860. if verb.lower() not in self._DM_COMMANDS:
  861. return False
  862. client = await self._get_chatto_client()
  863. if client is None:
  864. await self.send(chat_id=room_id, content="Chatto client is not connected.")
  865. return True
  866. argument = argument.strip()
  867. if not argument:
  868. await self.send(
  869. chat_id=room_id,
  870. content="Usage: /join <room-id or #name> | /leave <room-id or #name>",
  871. )
  872. return True
  873. error, target = await self._resolve_room_target(client, argument)
  874. if error or target is None:
  875. await self.send(chat_id=room_id, content=error or "Room lookup failed.")
  876. return True
  877. if verb.lower() == "/join":
  878. reply = await self._run_join(client, target)
  879. else:
  880. reply = await self._run_leave(client, target)
  881. await self.send(chat_id=room_id, content=reply)
  882. return True
  883. async def _resolve_room_target(
  884. self,
  885. client: ChattoClient,
  886. argument: str,
  887. ) -> tuple[str | None, RoomWithViewerState | None]:
  888. """Resolve a ``/join`` or ``/leave`` argument to a room.
  889. ``#name`` is looked up case-insensitively in a fresh directory scan
  890. (which also refreshes our name/kind caches); anything else is treated
  891. as a room ID and verified via GetRoom. An ambiguous name comes back as
  892. an error naming the candidates, so the admin can retry with an ID.
  893. """
  894. if not argument.startswith("#"):
  895. state = await client.get_room(argument)
  896. if state is None or state.room is None:
  897. return f"No room with ID '{argument}'.", None
  898. return None, state
  899. wanted = argument[1:].strip().casefold()
  900. # (state, room) pairs: a listed match's room is already narrowed here,
  901. # so the candidate listing below needs no fresh Optional dance.
  902. matches: list[tuple[RoomWithViewerState, Room]] = []
  903. for state in await client.list_rooms() or []:
  904. room_obj = state.room if state else None
  905. if room_obj and (room_obj.name or "").strip().casefold() == wanted:
  906. matches.append((state, room_obj))
  907. self._room_names[room_obj.id] = room_obj.name
  908. self._room_kinds[room_obj.id] = room_obj.kind
  909. if not matches:
  910. return f"No room named '{argument}'.", None
  911. if len(matches) > 1:
  912. candidates = "\n".join(f"• {room.name} ({room.id})" for _, room in matches)
  913. return (
  914. f"Several rooms are named '{argument}' — pick one by ID:\n{candidates}"
  915. ), None
  916. return None, matches[0][0]
  917. async def _run_join(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  918. """Join a room via RoomService/JoinRoom and track it as joined.
  919. An account that already holds membership (invited natively in Chatto)
  920. needs no JoinRoom call — it only gets seeded and added to the list.
  921. Channel-kind rooms additionally report their mention-list status,
  922. because a channel on neither list stays silent and this reply is
  923. where users copy the room ID from (see ``_room_join_hint``).
  924. """
  925. room_obj = state.room
  926. if room_obj is None:
  927. # Unreachable via _resolve_room_target: both of its paths only
  928. # return states whose room they already inspected.
  929. return "Chatto returned an empty room record — try again."
  930. label = f"'{room_obj.name}' ({room_obj.id})"
  931. joined_room = room_obj
  932. if not state.viewer_state.is_member:
  933. try:
  934. joined_room = await client.join_room(room_obj.id) or room_obj
  935. except ChattoError as exc:
  936. logger.warning("Chatto: /join failed for %s (%s)", room_obj.id, exc)
  937. return f"Could not join {label}: {exc}"
  938. self._room_names[joined_room.id] = joined_room.name
  939. self._room_kinds[joined_room.id] = joined_room.kind
  940. if joined_room.id not in self._joined_room_ids:
  941. # Same rule as _refresh_rooms: silent rooms are joined read-only
  942. # — seeding history nothing will ever answer would be waste.
  943. if self._answers_in_room(joined_room.id):
  944. await self._seed_room(joined_room.id)
  945. else:
  946. logger.info(
  947. "Chatto: %s is on neither mention list - joined read-only",
  948. label,
  949. )
  950. self._joined_room_ids.append(joined_room.id)
  951. if room_obj.kind != RoomKind.DM:
  952. head = (
  953. f"Already a member of {label}."
  954. if state.viewer_state.is_member
  955. else f"Joined {label}."
  956. )
  957. return f"{head}\n{self._room_join_hint(room_obj.id)}"
  958. if state.viewer_state.is_member:
  959. return f"Already a member of {label} — listening there."
  960. return f"Joined {label}."
  961. async def _run_leave(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  962. """Leave a room via RoomService/LeaveRoom and drop it from the joined list.
  963. Two rooms are refused: a DM conversation cannot be left, and leaving
  964. the configured home channel would silently break cron/notification
  965. delivery, which posts there through the standalone sender.
  966. """
  967. room_obj = state.room
  968. if room_obj is None:
  969. # Same invariant as _run_join: _resolve_room_target pre-inspects.
  970. return "Chatto returned an empty room record — try again."
  971. label = f"'{room_obj.name}' ({room_obj.id})"
  972. if room_obj.kind == RoomKind.DM:
  973. return "Direct messages cannot be left."
  974. home_id = (self.chatto_config.home_channel.value or "").strip()
  975. if home_id == room_obj.id:
  976. return (
  977. f"{label} is the configured home channel "
  978. "(CHATTO_HOME_CHANNEL); leaving it would break cron and "
  979. "notification delivery. Point CHATTO_HOME_CHANNEL elsewhere first."
  980. )
  981. try:
  982. left = await client.leave_room(room_obj.id)
  983. except ChattoError as exc:
  984. logger.warning("Chatto: /leave failed for %s (%s)", room_obj.id, exc)
  985. return f"Could not leave {label}: {exc}"
  986. if not left:
  987. return f"Chatto refused to leave {label}."
  988. if room_obj.id in self._joined_room_ids:
  989. self._joined_room_ids.remove(room_obj.id)
  990. # We are no longer part of this audience; keep no roster for it.
  991. self._evict_roster(room_obj.id)
  992. return f"Left {label}."
  993. def _room_join_hint(self, room_id: str) -> str:
  994. """The mention-list status appended to a channel-kind /join reply.
  995. Users do not know their room IDs by heart — this reply is where they
  996. copy them from, so a silent channel names both env vars verbatim,
  997. ready to paste into ~/.hermes/.env. Configuration resolves once at
  998. gateway startup, hence the restart note.
  999. """
  1000. policy = self._room_policy(room_id)
  1001. if policy == RoomPolicy.REQUIRE_MENTION:
  1002. return (
  1003. "This channel answers only @mentions "
  1004. "(listed in CHATTO_REQUIRE_MENTION_ROOMS)."
  1005. )
  1006. if policy == RoomPolicy.OPEN:
  1007. return (
  1008. "This channel answers every message "
  1009. "(listed in CHATTO_OPTIONAL_MENTION_ROOMS)."
  1010. )
  1011. return (
  1012. "This channel stays silent until you list its ID in"
  1013. " ~/.hermes/.env (then restart the gateway):\n"
  1014. f" CHATTO_REQUIRE_MENTION_ROOMS={room_id} <- answer only @mentions\n"
  1015. f" CHATTO_OPTIONAL_MENTION_ROOMS={room_id} <- answer every message"
  1016. )
  1017. # ------------------------------------------------------------------ #
  1018. # Inbound attachments
  1019. # ------------------------------------------------------------------ #
  1020. async def _download_attachment_bytes(self, url: str) -> bytes:
  1021. """Download an attachment, refusing to buffer more than the gateway cap.
  1022. The Content-Length header is checked first so an oversized asset is
  1023. rejected before a single chunk is read; the running total is re-checked
  1024. as chunks arrive, because a missing or lying header must not smuggle an
  1025. unbounded body past the cap.
  1026. """
  1027. max_bytes = get_inbound_media_max_bytes()
  1028. chunks: list[bytes] = []
  1029. total = 0
  1030. async with (
  1031. httpx.AsyncClient(
  1032. timeout=ChattoConstants.HTTP_TIMEOUT,
  1033. follow_redirects=True,
  1034. ) as http,
  1035. http.stream("GET", url) as resp,
  1036. ):
  1037. resp.raise_for_status()
  1038. declared = resp.headers.get("content-length")
  1039. if declared:
  1040. try:
  1041. declared_size = int(declared)
  1042. except ValueError:
  1043. logger.debug("Chatto: ignoring invalid Content-Length %r", declared)
  1044. else:
  1045. validate_inbound_media_size(
  1046. declared_size,
  1047. media_type="attachment",
  1048. max_bytes=max_bytes,
  1049. )
  1050. async for chunk in resp.aiter_bytes():
  1051. total += len(chunk)
  1052. validate_inbound_media_size(
  1053. total,
  1054. media_type="attachment",
  1055. max_bytes=max_bytes,
  1056. )
  1057. chunks.append(chunk)
  1058. return b"".join(chunks)
  1059. async def _cache_attachments(
  1060. self,
  1061. attachments: list[MessageAttachment],
  1062. ) -> tuple[list[str], list[str], list[str]]:
  1063. """Download message attachments into the gateway media cache.
  1064. Returns ``(media_urls, media_types, media_kinds)`` — the paths are
  1065. agent-visible cache paths, exactly what ``cache_media_bytes`` yields for
  1066. every other platform. A failing attachment is logged and skipped: the
  1067. message itself still reaches the agent.
  1068. """
  1069. media_urls: list[str] = []
  1070. media_types: list[str] = []
  1071. media_kinds: list[str] = []
  1072. for att in attachments:
  1073. url = att.asset_url.url if att.asset_url else ""
  1074. filename = att.filename
  1075. content_type = att.content_type
  1076. if not url:
  1077. # Videos are announced before transcoding finishes, so the
  1078. # signed URL can legitimately be missing on arrival.
  1079. logger.debug(
  1080. "Chatto: attachment '%s' has no asset URL yet, skipping",
  1081. filename,
  1082. )
  1083. continue
  1084. try:
  1085. data = await self._download_attachment_bytes(url)
  1086. cached = cache_media_bytes(
  1087. data,
  1088. filename=filename,
  1089. mime_type=content_type,
  1090. )
  1091. except Exception as e:
  1092. logger.warning(
  1093. "Chatto: failed to cache attachment '%s' (%s): %s",
  1094. filename,
  1095. content_type,
  1096. e,
  1097. )
  1098. continue
  1099. if cached is None:
  1100. logger.warning(
  1101. "Chatto: attachment '%s' (%s) could not be cached, skipping",
  1102. filename,
  1103. content_type,
  1104. )
  1105. continue
  1106. media_urls.append(cached.path)
  1107. media_types.append(cached.media_type)
  1108. media_kinds.append(cached.kind)
  1109. return media_urls, media_types, media_kinds
  1110. @staticmethod
  1111. def _message_type_for_media_kinds(media_kinds: list[str]) -> MessageType:
  1112. """Pick the MessageType for a set of cached attachment kinds."""
  1113. if "document" in media_kinds:
  1114. return MessageType.DOCUMENT
  1115. if "image" in media_kinds:
  1116. return MessageType.PHOTO
  1117. if "video" in media_kinds:
  1118. return MessageType.VIDEO
  1119. if "audio" in media_kinds:
  1120. return MessageType.AUDIO
  1121. return MessageType.TEXT
  1122. async def _room_kind_for(
  1123. self, client: ChattoClient, room_id: str
  1124. ) -> RoomKind | None:
  1125. """The room's kind, from cache or a fresh GetRoom lookup.
  1126. Returns ``None`` when the room cannot be resolved — the caller treats
  1127. that as "not dispatchable" rather than guessing a kind.
  1128. """
  1129. kind = self._room_kinds.get(room_id)
  1130. if kind is not None:
  1131. return kind
  1132. room_viewer_state = await client.get_room(room_id)
  1133. if room_viewer_state is None or room_viewer_state.room is None:
  1134. return None
  1135. kind = room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  1136. self._room_kinds[room_id] = kind
  1137. return kind
  1138. def _room_policy(self, room_id: str) -> RoomPolicy:
  1139. """Which of the mention lists a channel-kind room is on.
  1140. The two lists are mutually exclusive (enforced by
  1141. ``hermes_validate_config``), so membership decides: optional beats
  1142. require in the face of contradictory runtime config, and a room on
  1143. neither list stays silent. Callers that only need yes/no ask
  1144. ``_answers_in_room``, which delegates to the shared ``_room_answers_in``
  1145. the send tools use.
  1146. """
  1147. if room_id in self.chatto_config.optional_mention_rooms.value:
  1148. return RoomPolicy.OPEN
  1149. if room_id in self.chatto_config.require_mention_rooms.value:
  1150. return RoomPolicy.REQUIRE_MENTION
  1151. return RoomPolicy.SILENT
  1152. def _answers_in_room(self, room_id: str) -> bool:
  1153. """Whether inbound messages from this room reach the agent pipeline.
  1154. Delegates to the shared ``_room_answers_in``, which the send tools gate
  1155. on too — see there for the rule and why it exists only once. A room
  1156. that answers is never read-only (its policy is not SILENT), and an
  1157. unknown kind falls through to the mention lists rather than being
  1158. mistaken for a DM.
  1159. """
  1160. return _room_answers_in(
  1161. self.chatto_config, room_id, self._room_kinds.get(room_id)
  1162. )
  1163. def toolsets_for_source(self, source: SessionSource) -> list[str] | None:
  1164. """Restrict which toolsets a turn in a listed room may use.
  1165. ``CHATTO_ROOM_TOOLSETS`` holds ``room_id:toolset`` entries. A room with
  1166. at least one entry *replaces* the platform's toolset list for turns in
  1167. that room — Hermes' contract for this hook — so the entries have to name
  1168. every toolset the room should keep. A room without an entry returns
  1169. None, leaving ``platform_toolsets`` in charge. DM rooms are looked up
  1170. like any other room, and a thread turn carries its room's ID, so a room
  1171. entry covers its threads too.
  1172. BasePlatformAdapter override
  1173. """
  1174. room_id = str(getattr(source, "chat_id", "") or "")
  1175. if not room_id:
  1176. return None
  1177. by_room, _malformed = _parse_room_toolsets(
  1178. self.chatto_config.room_toolsets.value
  1179. )
  1180. return by_room.get(room_id) or None
  1181. async def _room_roster_context(
  1182. self, client: ChattoClient, room_id: str
  1183. ) -> _RoomRoster | None:
  1184. """Fetch the room's member roster as a fresh projection.
  1185. The agent only ever sees its prompt: without this block it cannot know
  1186. who else is in a channel, because unaddressed messages are dropped by
  1187. mention gating long before they could teach it a name. Fetched users go
  1188. into _user_cache so presence patching and mention resolution share one
  1189. store. Returns ``None`` on failure or when nothing renderable remains —
  1190. best-effort by design, a directory hiccup must never cost the turn.
  1191. """
  1192. try:
  1193. # list_room_members() in 0.5.0b4 returns member IDs only;
  1194. # batch_get_room_members() hydrates them into DirectoryMember.
  1195. member_id_list, page = await client.list_room_members(
  1196. room_id, limit=ChattoConstants.ROSTER_MEMBER_LIMIT
  1197. )
  1198. if not member_id_list:
  1199. return None
  1200. members = await client.batch_get_room_members(room_id, member_id_list)
  1201. except Exception:
  1202. logger.debug(
  1203. "Chatto: could not list members of room %s", room_id, exc_info=True
  1204. )
  1205. return None
  1206. logger.debug(
  1207. "Chatto: roster for room %s: %d members fetched, total_count=%d",
  1208. room_id,
  1209. len(members),
  1210. page.total_count,
  1211. )
  1212. member_ids: set[str] = set()
  1213. users: list[User] = []
  1214. for member in members:
  1215. user = member.user
  1216. if user is None or user.deleted:
  1217. continue
  1218. member_ids.add(user.id)
  1219. self._user_cache[user.id] = user
  1220. users.append(user)
  1221. entries = [
  1222. entry for entry in (self._roster_entry(user) for user in users) if entry
  1223. ]
  1224. if not entries:
  1225. logger.debug(
  1226. "Chatto: roster for room %s empty after filtering "
  1227. "(%d fetched, all deleted/self/without user)",
  1228. room_id,
  1229. len(members),
  1230. )
  1231. return None
  1232. logger.debug("Chatto: roster for room %s: %d entries", room_id, len(entries))
  1233. unfetched = max(0, page.total_count - len(members))
  1234. return _RoomRoster(member_ids=member_ids, unfetched=unfetched)
  1235. def _roster_entry(self, user: User) -> str:
  1236. """One roster entry, e.g. ``@bob (Bob Example, online)``.
  1237. Skips deleted users and our own account (the agent knows itself);
  1238. display name and presence are optional parts of the parenthetical.
  1239. """
  1240. if user.deleted:
  1241. return ""
  1242. if self.me is not None and user.id == self.me.id:
  1243. return ""
  1244. entry = f"@{user.login}"
  1245. details = [
  1246. part
  1247. for part in (
  1248. user.display_name,
  1249. _PRESENCE_LABELS.get(user.presence_status, ""),
  1250. )
  1251. if part
  1252. ]
  1253. if details:
  1254. entry += f" ({', '.join(details)})"
  1255. return entry
  1256. def _roster_line(self, room_id: str) -> str:
  1257. """Render the room's roster line from its cached projection."""
  1258. roster = self._rosters.get(room_id)
  1259. if roster is None:
  1260. return ""
  1261. users = [self._user_cache.get(member_id) for member_id in roster.member_ids]
  1262. entries = [
  1263. entry
  1264. for entry in (
  1265. self._roster_entry(user) for user in users if user is not None
  1266. )
  1267. if entry
  1268. ]
  1269. more = f" … and {roster.unfetched} more" if roster.unfetched else ""
  1270. return ", ".join(entries) + more
  1271. def _announce_roster(self, room_id: str, roster: _RoomRoster) -> None:
  1272. """Record a freshly fetched roster as the room's projection.
  1273. Bounded like _dispatched_ids: appending past the cap drops the oldest
  1274. room's projection alongside its deque entry.
  1275. """
  1276. if room_id not in self._roster_announced:
  1277. oldest = (
  1278. self._roster_announced.popleft()
  1279. if len(self._roster_announced) == self._roster_announced.maxlen
  1280. else None
  1281. )
  1282. self._roster_announced.append(room_id)
  1283. if oldest is not None:
  1284. self._rosters.pop(oldest, None)
  1285. self._rosters[room_id] = roster
  1286. async def _thread_context_for(
  1287. self,
  1288. client: ChattoClient,
  1289. *,
  1290. room_id: str,
  1291. thread_root_event_id: str,
  1292. current_message_id: str,
  1293. source: Any,
  1294. ) -> str:
  1295. """The thread's earlier messages, delivered once per thread.
  1296. A Hermes thread session is keyed on the thread root and starts empty,
  1297. so the turn that opens a thread is answered with nothing but the reply
  1298. itself. The reported case: a cron job posts into a channel, its echo
  1299. is filtered as a self-event and never reaches a session, and a human
  1300. replies — rooting a thread whose root the agent has never seen. Without
  1301. this block the agent answers a message it cannot read.
  1302. Gated on ``thread_root_event_id``, not on the resolved ``thread_id``:
  1303. a fresh room message is anchored to itself (see _admit_and_build), and
  1304. that thread does not exist yet, so there is nothing to fetch. DMs never
  1305. thread and never seed.
  1306. The cursor is kept twice: in memory for this process, and on the session
  1307. for the next one. Only the second one survives a restart, and it is not
  1308. a redundant copy — a session's frontier is *not* derivable from the
  1309. thread's messages, because the bot's own messages belong to no session
  1310. while the previous turn's trigger looks exactly like one the session
  1311. holds. Rebuilding a partition from the fetch therefore lands on the
  1312. wrong message and skips the very output this exists to deliver.
  1313. Best-effort by design, like the roster: a failed lookup leaves the
  1314. thread unseeded so the next turn retries.
  1315. """
  1316. if not thread_root_event_id:
  1317. return ""
  1318. session_key = self._session_key_for(source)
  1319. # The cursor is resolved *before* the fetch, because it anchors it. That
  1320. # is what makes a long thread work: the server returns the oldest messages
  1321. # past the anchor rather than the newest ones in the thread, so a thread
  1322. # that grew past the fetch limit still answers with what the session is
  1323. # missing instead of leaving the cursor outside the window.
  1324. cursor = self._seeded_threads.get(thread_root_event_id, _UNSEEDED)
  1325. if cursor is _UNSEEDED:
  1326. resumed = self._persisted_cursor(session_key, _UNSEEDED)
  1327. if isinstance(resumed, str):
  1328. # A cursor an earlier process left behind: it outlived that
  1329. # process with the session, so the thread goes on delivering its
  1330. # tail.
  1331. self._record_thread_seeded(thread_root_event_id, resumed)
  1332. cursor = resumed
  1333. anchored = cursor if isinstance(cursor, str) else ""
  1334. history = await self._thread_history(
  1335. client,
  1336. room_id=room_id,
  1337. thread_root_event_id=thread_root_event_id,
  1338. after=anchored,
  1339. )
  1340. if history is None:
  1341. logger.debug(
  1342. "Chatto: dispatching into thread %s without history (lookup failed)",
  1343. thread_root_event_id,
  1344. )
  1345. return ""
  1346. if anchored:
  1347. # Everything the anchored page holds landed after the cursor, so it is
  1348. # the tail — no cutting point to find inside the window.
  1349. return self._seed_thread_tail(
  1350. thread_root_event_id,
  1351. history,
  1352. current_message_id,
  1353. session_key=session_key,
  1354. )
  1355. if self._thread_session_exists(source):
  1356. # A session that survived a restart but carries no cursor: a thread
  1357. # whose first turn had nothing to seed wrote no cursor (there was no
  1358. # session to write it to) and never got a second turn to retry on.
  1359. #
  1360. # Its frontier is not derivable from the message list, so this
  1361. # delivers the one thing that is provably at risk — the bot's own
  1362. # messages, which belong to no session — and leaves the people's
  1363. # messages alone, since those became turns. Duplicating the former
  1364. # is possible (a first seed that did carry them, same lost second
  1365. # turn) and is bounded to that one block; losing it is the common
  1366. # case and permanent. The cursor is written either way, so the thread
  1367. # is blind once, not for the rest of its life.
  1368. own = [m for m in history if m.id != current_message_id and self._is_own(m)]
  1369. logger.debug(
  1370. "Chatto: thread %s has a session without a seed cursor; "
  1371. "re-delivering %d own message(s)",
  1372. thread_root_event_id,
  1373. len(own),
  1374. )
  1375. established = self._seeded_through(history, own, current_message_id)
  1376. if established is not None:
  1377. self._record_thread_seeded(thread_root_event_id, established)
  1378. self._persist_thread_cursor(
  1379. session_key, thread_root_event_id, established
  1380. )
  1381. return self._thread_context_block(own)
  1382. # First turn into this thread: the session starts empty, so hand it the
  1383. # whole thread before the reply.
  1384. earlier = [m for m in history if m.id != current_message_id]
  1385. self._remember_thread_cursor(
  1386. session_key,
  1387. thread_root_event_id,
  1388. self._seeded_through(history, earlier, current_message_id),
  1389. delivered=earlier,
  1390. )
  1391. return self._thread_context_block(earlier)
  1392. @staticmethod
  1393. def _seeded_through(
  1394. history: list[Message], delivered: list[Message], current_message_id: str
  1395. ) -> str:
  1396. """How far this turn's session now reaches.
  1397. The trigger is excluded from the *block* — it is the message text — but
  1398. the session holds it, so the cursor passes it too. Leaving it behind
  1399. would hand the next turn the previous question a second time, as an
  1400. `[Earlier in this thread]` line beside the conversation that already
  1401. contains it.
  1402. The trigger is also the fallback when the fetched window does not list
  1403. it: the session holds this turn's own message either way. That is safe
  1404. because the fetch is anchored *at* the cursor rather than sliced around
  1405. it — a cursor names a boundary, not a position inside the window, so one
  1406. the window does not contain is still a usable cursor. That is what lets
  1407. this be a plain ``str`` instead of "maybe unknowable".
  1408. """
  1409. if any(m.id == current_message_id for m in history):
  1410. return current_message_id
  1411. return delivered[-1].id if delivered else current_message_id
  1412. def _seed_thread_tail(
  1413. self,
  1414. thread_root_event_id: str,
  1415. history: list[Message],
  1416. current_message_id: str,
  1417. *,
  1418. session_key: str,
  1419. ) -> str:
  1420. """Deliver what landed in an already-seeded thread since the cursor.
  1421. This is the agent's own output the session never saw: a message it posted
  1422. into the thread through a tool, whose realtime echo is filtered as a
  1423. self-event. Without it the next human message in that thread is answered
  1424. by an agent that does not know what it said.
  1425. ``history`` is anchored at the cursor, so every message in it is by
  1426. definition one the session does not hold — there is no cut point to find
  1427. inside the window, and no case where the window cannot answer.
  1428. """
  1429. unseen = [m for m in history if m.id != current_message_id]
  1430. # The cursor moves even when the trigger was all that arrived: it is in
  1431. # the session, and a cursor left behind it would hand the next turn the
  1432. # previous question a second time.
  1433. self._remember_thread_cursor(
  1434. session_key,
  1435. thread_root_event_id,
  1436. self._seeded_through(history, unseen, current_message_id),
  1437. delivered=unseen,
  1438. )
  1439. return self._thread_context_block(unseen)
  1440. async def _thread_history(
  1441. self,
  1442. client: ChattoClient,
  1443. *,
  1444. room_id: str,
  1445. thread_root_event_id: str,
  1446. after: str = "",
  1447. ) -> list[Message] | None:
  1448. """Fetch a thread's messages oldest-first, or ``None`` if the lookup failed.
  1449. ``after`` anchors the page at a cursor instead of at the thread's start,
  1450. and that is the whole point: the server then returns the *oldest* messages
  1451. past that cursor rather than the newest ones in the thread. A thread that
  1452. has grown past the fetch limit therefore still answers with exactly what
  1453. the session is missing, where an unanchored page would have left the
  1454. cursor outside the window and the turn with nothing to deliver.
  1455. Two things follow from the anchor, both from the server's own handler: the
  1456. root is not part of an anchored page (``IncludeRoot`` is false whenever
  1457. ``after`` is set), and it is not needed either — a cursor means
  1458. everything up to and including it is already in the session. So the extra
  1459. root fetch is skipped, which is one RPC fewer per turn than the unanchored
  1460. path.
  1461. When the gap is larger than the limit the page holds only its oldest
  1462. slice and the cursor stops at the last message delivered; the next turn
  1463. continues from there. A backlog drains over turns rather than in one, and
  1464. nothing is skipped either way.
  1465. """
  1466. try:
  1467. page = await client.get_thread_events(
  1468. room_id,
  1469. thread_root_event_id,
  1470. limit=ChattoConstants.THREAD_CONTEXT_MESSAGE_LIMIT,
  1471. after=after or None,
  1472. )
  1473. except Exception:
  1474. logger.debug(
  1475. "Chatto: get thread events failed for %s/%s",
  1476. room_id,
  1477. thread_root_event_id,
  1478. exc_info=True,
  1479. )
  1480. return None
  1481. messages = [ev.message for ev in page.events if ev.message is not None]
  1482. if not after and not any(m.id == thread_root_event_id for m in messages):
  1483. # The thread root is fetched explicitly when the unanchored timeline
  1484. # omits it: a cron message is a plain room message until someone
  1485. # replies to it, and whether the server lists it back as the thread's
  1486. # first event is not something the client signature promises.
  1487. messages = (
  1488. await self._thread_root_message(
  1489. client, room_id=room_id, thread_root_event_id=thread_root_event_id
  1490. )
  1491. + messages
  1492. )
  1493. return _oldest_first(messages)
  1494. async def _thread_root_message(
  1495. self, client: ChattoClient, *, room_id: str, thread_root_event_id: str
  1496. ) -> list[Message]:
  1497. """The thread root as a list, so a miss concatenates cleanly.
  1498. Best-effort: an unknown root costs nothing but the missing root line.
  1499. """
  1500. try:
  1501. root = await client.get_message(
  1502. room_id=room_id, event_id=thread_root_event_id
  1503. )
  1504. except Exception:
  1505. logger.debug(
  1506. "Chatto: get thread root failed for %s/%s",
  1507. room_id,
  1508. thread_root_event_id,
  1509. exc_info=True,
  1510. )
  1511. return []
  1512. return [root] if root is not None and not root.deleted_at else []
  1513. def _remember_thread_cursor(
  1514. self,
  1515. session_key: str,
  1516. thread_root_event_id: str,
  1517. cursor: str,
  1518. *,
  1519. delivered: list[Message],
  1520. ) -> None:
  1521. """Record how far a thread's session reaches, and mirror it if it must.
  1522. The in-memory map is authoritative while this process lives. The session
  1523. copy exists for one thing — a restart, where the map is empty and the
  1524. session survived — and it is written when either of two things holds:
  1525. - the turn put the bot's own output into the session. That is the one
  1526. thing a later turn cannot recover from the message list, so it is the
  1527. one cursor that has to outlive us. Every other turn's frontier is the
  1528. newest message that is not ours, and a restart that loses such a cursor
  1529. delivers nothing, which is right because that turn delivered nothing
  1530. worth losing.
  1531. - an earlier turn's cursor is still waiting for a session to land on. A
  1532. thread's first turn has none — and its seed is exactly the case above,
  1533. a cron message delivered to a session that did not exist yet. By the
  1534. second turn the session exists.
  1535. Writing unconditionally would cost a full routing-table rewrite per turn
  1536. (see _persist_thread_cursor) to save a case that costs nothing.
  1537. """
  1538. self._record_thread_seeded(thread_root_event_id, cursor)
  1539. unrecoverable = any(self._is_own(message) for message in delivered)
  1540. if unrecoverable or thread_root_event_id in self._unpersisted_threads:
  1541. self._persist_thread_cursor(session_key, thread_root_event_id, cursor)
  1542. def _persist_thread_cursor(
  1543. self, session_key: str, thread_root_event_id: str, cursor: str
  1544. ) -> None:
  1545. """Mirror the cursor onto the session, remembering a refusal.
  1546. ``set_session_metadata`` rewrites the whole routing index on every call,
  1547. which is why the caller restricts this to the turns that need it. A
  1548. refusal costs nothing here — the in-memory cursor carries the thread
  1549. until the next process — so it is remembered and retried on the next turn
  1550. rather than logged away, because a cursor that never lands is exactly the
  1551. cursor a restart needs.
  1552. """
  1553. store = getattr(self, "_session_store", None)
  1554. writer = getattr(store, "set_session_metadata", None)
  1555. if not callable(writer):
  1556. return
  1557. try:
  1558. landed = bool(writer(session_key, _CURSOR_META_KEY, cursor))
  1559. except Exception:
  1560. logger.debug(
  1561. "Chatto: persisting the seed cursor for %s failed",
  1562. session_key,
  1563. exc_info=True,
  1564. )
  1565. return
  1566. if landed:
  1567. self._unpersisted_threads.discard(thread_root_event_id)
  1568. else:
  1569. # No session under that key yet, which is the expected shape of a
  1570. # thread's first turn.
  1571. self._unpersisted_threads.add(thread_root_event_id)
  1572. def _persisted_cursor(self, session_key: str, default: _T) -> str | _T:
  1573. """The cursor a previous process left on this session, or ``default``.
  1574. Best-effort bookkeeping, so every failure answers ``default``: a missing
  1575. store, a store without metadata support, a rejected read. That degrades
  1576. to "this thread's frontier is unknown", never to a failed turn.
  1577. """
  1578. store = getattr(self, "_session_store", None)
  1579. reader = getattr(store, "get_session_metadata", None)
  1580. if not callable(reader):
  1581. return default
  1582. try:
  1583. # Duck-typed: the store is optional and may not carry metadata at
  1584. # all, so its value comes back as whatever it is.
  1585. value: Any = reader(session_key, _CURSOR_META_KEY, None)
  1586. except Exception:
  1587. logger.debug(
  1588. "Chatto: reading the seed cursor for %s failed",
  1589. session_key,
  1590. exc_info=True,
  1591. )
  1592. return default
  1593. return value if value is not None else default
  1594. async def _reply_target(
  1595. self, client: ChattoClient, room_id: str, in_reply_to: str
  1596. ) -> Message | None:
  1597. """The message a reply points at, or ``None`` when it cannot be read.
  1598. Best-effort on purpose: a deleted or unreadable target costs the
  1599. context line, not the turn — an unanswered reply is worse than one
  1600. answered without its quote.
  1601. """
  1602. try:
  1603. target = await client.get_message(room_id=room_id, event_id=in_reply_to)
  1604. except Exception:
  1605. logger.debug(
  1606. "Chatto: reply target %s/%s could not be read",
  1607. room_id,
  1608. in_reply_to,
  1609. exc_info=True,
  1610. )
  1611. return None
  1612. if target is None or target.deleted_at:
  1613. return None
  1614. return target
  1615. def _is_own(self, message: Message) -> bool:
  1616. """Whether this message is one the bot itself posted."""
  1617. return self.me is not None and message.actor_id == self.me.id
  1618. def _record_thread_seeded(
  1619. self, thread_root_event_id: str, last_delivered_id: str
  1620. ) -> None:
  1621. """Note that this thread's session holds its history up to that message.
  1622. Re-inserting keeps the map insertion-ordered, which is what the cap below
  1623. evicts from: the least recently touched thread.
  1624. """
  1625. self._seeded_threads.pop(thread_root_event_id, None)
  1626. self._seeded_threads[thread_root_event_id] = last_delivered_id
  1627. while len(self._seeded_threads) > ChattoConstants.SEEN_CAP:
  1628. self._seeded_threads.pop(next(iter(self._seeded_threads)))
  1629. def _thread_session_exists(self, source: Any) -> bool:
  1630. """Whether the gateway already has a session for this source.
  1631. Kept as the thread path's own name: it answers the same question as
  1632. ``_session_exists`` and delegates to it, so the two paths cannot
  1633. disagree about what "a session exists" means.
  1634. """
  1635. return self._session_exists(source)
  1636. async def _room_context_for(
  1637. self,
  1638. client: ChattoClient,
  1639. *,
  1640. room_id: str,
  1641. trigger: Message,
  1642. source: Any,
  1643. ) -> str:
  1644. """The room's earlier messages, delivered when a room session starts.
  1645. A fresh room message roots its own session (see _admit_and_build), so
  1646. the first turn into a room is answered with nothing but that message —
  1647. even when the room has been talking for hours and even when the bot
  1648. itself posted there. The reported case: a human replies to the bot's
  1649. message without opening a thread, and the agent answers a conversation
  1650. it has never seen.
  1651. The block is bounded by the same caps as the thread seed, and it is
  1652. skipped as soon as the session holds a turn: the goal is to open a room
  1653. conversation with its recent context, not to re-deliver the room's
  1654. history on every message.
  1655. Seeding is anchored on the trigger, not on a per-room cursor: every
  1656. fresh room message opens a new session, so a cursor written for one
  1657. session's frontier would hand the next message's session a block
  1658. written for the first one's. The trigger-anchored fetch makes the
  1659. block "what the room said before this message", which is the question
  1660. a session start actually asks.
  1661. """
  1662. if self._session_exists(source):
  1663. return ""
  1664. try:
  1665. page, _anchor_index = await client.get_room_events_around(
  1666. room_id, trigger.id, limit=ChattoConstants.THREAD_CONTEXT_MESSAGE_LIMIT
  1667. )
  1668. except Exception:
  1669. logger.debug(
  1670. "Chatto: room context lookup failed for %s/%s",
  1671. room_id,
  1672. trigger.id,
  1673. exc_info=True,
  1674. )
  1675. return ""
  1676. messages = [ev.message for ev in page.events if ev.message is not None]
  1677. # The page carries its own user directory, which answers the author
  1678. # names in the block without a member-list call — the same hydration
  1679. # the read tools use for a fetched timeline.
  1680. for user_id, user in page.users_by_id.items():
  1681. self._user_cache.setdefault(user_id, user)
  1682. # ``around`` serves both directions of the trigger, and a session
  1683. # start is answered with the past, not the future: newer messages are
  1684. # not "earlier", and including one would hand the agent a message the
  1685. # room may still be typing around. Age is compared by time rather
  1686. # than by position, because the page's order is display order, not a
  1687. # promise about either side of the anchor.
  1688. trigger_time = trigger.created_at or datetime.min.replace(tzinfo=UTC)
  1689. earlier = [
  1690. m
  1691. for m in _oldest_first(messages)
  1692. if m.id != trigger.id
  1693. and not m.deleted_at
  1694. and (m.created_at or datetime.min.replace(tzinfo=UTC)) <= trigger_time
  1695. ]
  1696. return self._earlier_context_block(earlier, "[Earlier in this room]")
  1697. def _session_exists(self, source: Any) -> bool:
  1698. """Whether the gateway already has a session for this source.
  1699. The gateway's own routing index is the authority on "does this
  1700. conversation already exist" — it is persistent (state.db), so unlike
  1701. the in-memory dedup state it answers correctly after a restart.
  1702. Returns False when no store is wired (tests, or a startup path before
  1703. ``set_session_store`` runs) so we fail open and seed.
  1704. """
  1705. store = getattr(self, "_session_store", None)
  1706. if store is None:
  1707. return False
  1708. return store.peek_session_id(self._session_key_for(source)) is not None
  1709. def _thread_context_block(self, messages: list[Message]) -> str:
  1710. """Render earlier thread messages as the agent's reference block.
  1711. Empty when there is nothing to say — a brand-new thread has no earlier
  1712. messages, and that is not worth a header. Over budget, the oldest
  1713. messages go first: the reply's immediate predecessors are what the
  1714. turn is about.
  1715. """
  1716. return self._earlier_context_block(messages, "[Earlier in this thread]")
  1717. def _earlier_context_block(self, messages: list[Message], header: str) -> str:
  1718. """Render earlier messages as one reference block under ``header``.
  1719. Shared by the thread and the room seed: both answer the same question
  1720. ("what did this conversation say before the trigger"), so both get the
  1721. same rendering, the same caps and the same own/verified labelling — two
  1722. copies of one renderer would drift until a thread and a room disagreed
  1723. about what a quoted message looks like.
  1724. """
  1725. entries: list[str] = []
  1726. for message in messages:
  1727. entry = self._thread_message_entry(message)
  1728. if entry:
  1729. entries.append(entry)
  1730. if not entries:
  1731. return ""
  1732. dropped = 0
  1733. while (
  1734. entries
  1735. and len("\n".join(entries)) > ChattoConstants.THREAD_CONTEXT_CHAR_LIMIT
  1736. ):
  1737. entries.pop(0)
  1738. dropped += 1
  1739. if not entries:
  1740. return ""
  1741. body = "\n".join(entries)
  1742. omitted = f"… {dropped} earlier message(s) omitted\n" if dropped else ""
  1743. return f"{omitted}{header}\n{body}"
  1744. def _thread_message_entry(self, message: Message) -> str:
  1745. """One rendered message for an earlier-context block, or ``""``.
  1746. Attachment-only messages render empty: the block is text context, and
  1747. inventing a placeholder for a picture the agent cannot see here would
  1748. be noise.
  1749. """
  1750. body = (message.body or "").strip()
  1751. if not body:
  1752. return ""
  1753. me = self.me
  1754. user = self._user_cache.get(message.actor_id)
  1755. if me is not None and message.actor_id == me.id:
  1756. # The agent's own output — often a cron message it never saw
  1757. # arrive. Labelling it keeps "I said this" distinguishable from a
  1758. # third party talking.
  1759. return f"{me.login} (this bot): {body}"
  1760. author = f"@{user.login}" if user else f"@{message.actor_id}"
  1761. if not self._is_authorized(message.actor_id):
  1762. # Auth gates the trigger message only; the rest of a shared thread
  1763. # is reference text from people who may not be on the allowlist,
  1764. # so it is marked as unverified rather than presented as trusted
  1765. # input. An unknown author lands here too — fail closed.
  1766. return f"{author} (unverified): {body}"
  1767. return f"{author}: {body}"
  1768. def _is_authorized(self, actor_id: str) -> bool:
  1769. """Whether a Chatto user may talk to the agent, by user ID.
  1770. The allowlist test itself, without the logging _check_auth adds: a
  1771. rendering path asks the same question about someone quoted into the
  1772. prompt, where denial is a normal sight rather than an event worth a
  1773. warning. IDs only — a login entry would pass this intake but fail the
  1774. gateway's fresh-role recheck, which matches raw IDs, and the message
  1775. would be silently dropped between the two gates.
  1776. """
  1777. if self.chatto_config.allow_all_users.value:
  1778. return True
  1779. return actor_id in self.chatto_config.allowed_users.value
  1780. def _interactive_prompt_expired(self, prompt: Any) -> bool:
  1781. """Whether an interactive prompt has passed its expiry deadline."""
  1782. try:
  1783. return time.monotonic() > float(prompt.expires_at)
  1784. except (TypeError, ValueError, AttributeError):
  1785. return False
  1786. async def _try_handle_interactive_reaction(
  1787. self,
  1788. room_id: Any,
  1789. message_id: Any,
  1790. emoji: Any,
  1791. actor_id: Any,
  1792. ) -> bool:
  1793. """Route a reaction on a tracked interactive prompt.
  1794. Returns True when the message is a tracked prompt (consumed), False
  1795. otherwise so the caller forwards normally.
  1796. """
  1797. if not room_id or not message_id or not emoji or not actor_id:
  1798. return False
  1799. room_id = str(room_id)
  1800. message_id = str(message_id)
  1801. # Keep the raw form for the log: the server delivers shortcode names
  1802. # ("heavy_check_mark"), and a decoded-only log would hide exactly the
  1803. # name a client actually picked.
  1804. raw_emoji = str(emoji)
  1805. decoded = _SHORTCODE_TO_PROMPT_EMOJI.get(raw_emoji, raw_emoji)
  1806. emoji = _normalize_reaction_emoji(decoded)
  1807. actor_id = str(actor_id)
  1808. is_clarify = message_id in self._clarify_prompts
  1809. is_approval = message_id in self._approval_prompts
  1810. if not is_clarify and not is_approval:
  1811. return False
  1812. logger.debug(
  1813. "Chatto: reaction on prompt card %s: %s (raw %r)",
  1814. message_id,
  1815. emoji,
  1816. raw_emoji,
  1817. )
  1818. if is_clarify:
  1819. prompt = self._clarify_prompts.get(message_id)
  1820. else:
  1821. prompt = self._approval_prompts.get(message_id)
  1822. if prompt is None:
  1823. return False
  1824. # Room must match.
  1825. if str(getattr(prompt, "chat_id", "")) != room_id:
  1826. logger.debug(
  1827. "Chatto: reaction on prompt %s ignored - room %s, card lives in %s",
  1828. message_id,
  1829. room_id,
  1830. getattr(prompt, "chat_id", ""),
  1831. )
  1832. return True
  1833. # Expiry handling.
  1834. if self._interactive_prompt_expired(prompt):
  1835. try:
  1836. await self.edit_message(
  1837. room_id, message_id, "⏰ This prompt has expired."
  1838. )
  1839. except Exception:
  1840. logger.debug("Chatto: expired prompt edit failed", exc_info=True)
  1841. if is_clarify:
  1842. self._clarify_prompts.pop(message_id, None)
  1843. cid = getattr(prompt, "clarify_id", None)
  1844. if cid is not None:
  1845. self._clarify_id_to_message.pop(cid, None)
  1846. else:
  1847. self._approval_prompts.pop(message_id, None)
  1848. return True
  1849. # Authorization (fail-closed).
  1850. if not self._is_authorized(actor_id):
  1851. logger.debug(
  1852. "Chatto: reaction on prompt %s by unauthorized actor %s ignored",
  1853. message_id,
  1854. actor_id,
  1855. )
  1856. return True
  1857. # Double-click guard.
  1858. if getattr(prompt, "resolved", False):
  1859. logger.debug(
  1860. "Chatto: prompt %s already resolved - reaction ignored", message_id
  1861. )
  1862. return True
  1863. if is_clarify and getattr(prompt, "awaiting_text", False):
  1864. return True
  1865. user = self._user_cache.get(actor_id)
  1866. user_label = (
  1867. getattr(user, "name", None) or getattr(user, "login", None) or actor_id
  1868. )
  1869. if is_clarify:
  1870. from tools import clarify_gateway # type: ignore[import-not-found]
  1871. choices = list(getattr(prompt, "choices", []) or [])
  1872. logger.debug(
  1873. "Chatto: clarify prompt %s accepts: %s",
  1874. message_id,
  1875. [*choices, "Other"],
  1876. )
  1877. if emoji == _OTHER_EMOJI_KEY:
  1878. prompt.awaiting_text = True # type: ignore[assignment]
  1879. try:
  1880. clarify_gateway.mark_awaiting_text(prompt.clarify_id) # type: ignore[attr-defined]
  1881. except Exception:
  1882. logger.debug("Chatto: mark_awaiting_text failed", exc_info=True)
  1883. try:
  1884. await self.edit_message(
  1885. room_id, message_id, f"awaiting text from {user_label}"
  1886. )
  1887. except Exception:
  1888. logger.debug("Chatto: prompt edit failed", exc_info=True)
  1889. return True
  1890. if emoji in _NUMBER_EMOJI_KEYS:
  1891. idx = _NUMBER_EMOJI_KEYS.index(emoji)
  1892. if 0 <= idx < len(choices):
  1893. choice = choices[idx]
  1894. prompt.resolved = True
  1895. self._clarify_prompts.pop(message_id, None)
  1896. cid = getattr(prompt, "clarify_id", None) # type: ignore[arg-type]
  1897. if cid is not None:
  1898. self._clarify_id_to_message.pop(cid, None)
  1899. try:
  1900. clarify_gateway.resolve_gateway_clarify(str(cid), choice)
  1901. except Exception:
  1902. logger.exception("Chatto: resolve_gateway_clarify failed")
  1903. try:
  1904. await self.edit_message(
  1905. room_id,
  1906. message_id,
  1907. f"✅ {user_label} chose: {choice}",
  1908. )
  1909. except Exception:
  1910. logger.debug("Chatto: prompt edit failed", exc_info=True)
  1911. return True
  1912. # Invalid emoji feedback — name the options, so a rejected
  1913. # reaction teaches the valid ones instead of just refusing.
  1914. offered = [
  1915. _PROMPT_NUMBER_EMOJIS[i]
  1916. for i in range(min(len(choices), len(_PROMPT_NUMBER_EMOJIS)))
  1917. ]
  1918. try:
  1919. await self.send(
  1920. room_id,
  1921. "That reaction isn't a valid option for this prompt. "
  1922. f"React with {', '.join([*offered, _PROMPT_OTHER_EMOJI])}.",
  1923. )
  1924. except Exception:
  1925. logger.debug("Chatto: invalid reaction feedback failed", exc_info=True)
  1926. return True
  1927. # Approval prompt.
  1928. choices_map = getattr(prompt, "choices_map", {}) or {}
  1929. logger.debug(
  1930. "Chatto: approval prompt %s accepts: %s",
  1931. message_id,
  1932. [*choices_map],
  1933. )
  1934. if emoji in choices_map:
  1935. choice = choices_map[emoji]
  1936. prompt.resolved = True
  1937. self._approval_prompts.pop(message_id, None)
  1938. try:
  1939. import tools.approval as approval_mod
  1940. approval_mod.resolve_gateway_approval(
  1941. str(getattr(prompt, "session_key", "")), choice
  1942. )
  1943. except Exception:
  1944. logger.exception("Chatto: resolve_gateway_approval failed")
  1945. try:
  1946. await self.edit_message(
  1947. room_id, message_id, f"✅ {user_label}: {choice}"
  1948. )
  1949. except Exception:
  1950. logger.debug("Chatto: prompt edit failed", exc_info=True)
  1951. return True
  1952. # Invalid emoji feedback — the card's legend is the shortest correct
  1953. # list of what *is* valid here, so repeat it verbatim.
  1954. legend = ", ".join(f"{key} {choice}" for key, choice in choices_map.items())
  1955. try:
  1956. await self.send(
  1957. room_id,
  1958. "That reaction isn't a valid option for this prompt. "
  1959. f"Valid on this card: {legend}.",
  1960. )
  1961. except Exception:
  1962. logger.debug("Chatto: invalid reaction feedback failed", exc_info=True)
  1963. return True
  1964. def _evict_roster(self, room_id: str) -> None:
  1965. """Drop all roster state for a room.
  1966. Called on membership changes (user_joined/left_room), when we leave a
  1967. room ourselves, and on reconnect. The subscribe snapshot carries the
  1968. room and user directory but no presence, and the adapter does not
  1969. request it — so a discarded cache is what forces one honest refetch.
  1970. """
  1971. try:
  1972. self._roster_announced.remove(room_id)
  1973. except ValueError:
  1974. pass
  1975. self._rosters.pop(room_id, None)
  1976. async def _roster_for_room(self, client: ChattoClient, *, room_id: str) -> str:
  1977. """The room's roster line for this turn — delivered on every turn.
  1978. Threads hold isolated sessions and the agent only sees
  1979. channel_context per dispatch, so each channel turn carries the current
  1980. audience rather than deduplicating it. The projection exists to spare
  1981. the directory, not the prompt: presence patches land in _user_cache
  1982. in place, membership events or a reconnect evict the room so its next
  1983. turn refetches once. An unprojected room retries on its next turn
  1984. until a lookup succeeds.
  1985. """
  1986. if room_id not in self._roster_announced:
  1987. fetched = await self._room_roster_context(client, room_id)
  1988. if fetched is None:
  1989. return ""
  1990. self._announce_roster(room_id, fetched)
  1991. return self._roster_line(room_id)
  1992. async def _dispatch_message_posted(
  1993. self, payload: MessagePostedEvent, event_id: str
  1994. ) -> None:
  1995. # Respond-room gate first: read-only memberships must not cost a
  1996. # single API call, so this runs before fetch_message and _get_chatto_client.
  1997. if not self._answers_in_room(payload.room_id):
  1998. logger.debug(
  1999. "Chatto: message from read-only room %s ignored", payload.room_id
  2000. )
  2001. return
  2002. client = await self._get_chatto_client()
  2003. if client is None:
  2004. logger.warning("Chatto: dropping message - no client available")
  2005. return
  2006. logger.debug("Chatto WS: 'message_posted' payload:%s", payload)
  2007. message = await client.get_message(room_id=payload.room_id, event_id=event_id)
  2008. if message is None or message.deleted_at:
  2009. return
  2010. message_body = message.body or ""
  2011. logger.debug("message: %s", message)
  2012. # A message carrying only an image/PDF has an empty body — dropping it
  2013. # here is what made attachments sent to Hermes disappear silently.
  2014. if not message_body and not message.attachments:
  2015. return
  2016. event = await self._admit_and_build(
  2017. client,
  2018. room_id=payload.room_id,
  2019. message=message,
  2020. source_message_id=event_id,
  2021. thread_root_event_id=payload.thread_root_event_id or None,
  2022. mentions=_Mentions.from_payload(
  2023. payload.mentions, self.me.id if self.me else ""
  2024. ),
  2025. )
  2026. if event is None:
  2027. return
  2028. self._remember_dispatched(event.message_id or "")
  2029. logger.info("Chatto: dispatching message to Hermes")
  2030. await self.handle_message(event)
  2031. return
  2032. def _remember_dispatched(self, message_id: str) -> None:
  2033. """Record a message ID as handed to the gateway, capped like _seen."""
  2034. if not message_id:
  2035. return
  2036. self._dispatched_ids.append(message_id)
  2037. def _edit_is_fresh(self, message: Message) -> bool:
  2038. """Whether this edit is young enough to still be processed.
  2039. Age is measured against the posting time, so an edit to an hours-old
  2040. message cannot resurrect a settled conversation even when it arrives
  2041. right now.
  2042. """
  2043. if message.created_at is None or message.updated_at is None:
  2044. return True
  2045. age_seconds = (message.updated_at - message.created_at).total_seconds()
  2046. return age_seconds <= self.chatto_config.edit_window.value
  2047. def _session_key_for(self, source) -> str:
  2048. """The gateway's own session key for this source.
  2049. Delegates to the base class rather than calling ``build_session_key``
  2050. itself. A hand-built key has to be right about two things this one was
  2051. not: the routing identity has to be pinned first (``_canonicalize``), and
  2052. the key has to carry the serving profile's namespace. Without the second,
  2053. a multiplexed gateway keys every bot into ``agent:main:`` and the derived
  2054. key names a session nobody is running — which made
  2055. ``_thread_session_exists`` answer False for a live thread session, and
  2056. would make ``cancel_session_processing`` a no-op on an edited message.
  2057. """
  2058. return self._source_session_key(source)
  2059. async def _dispatch_message_edited(self, payload: Any) -> None:
  2060. """Route an inbound edit according to the edit-dispatch contract.
  2061. Three outcomes for the edited message:
  2062. - currently being processed → cancel that turn and re-dispatch with
  2063. the corrected text (the cancelled turn reports 🚫 via its
  2064. CANCELLED outcome hook),
  2065. - never dispatched (e.g. a forgotten @mention added later) → re-run
  2066. the admission gates against the new body and answer for real,
  2067. - already answered → stay answered.
  2068. Edits whose text parses as a DM membership command are dropped: the
  2069. command ran when the message was posted and must not run again.
  2070. """
  2071. if not self.chatto_config.edit_dispatch.value:
  2072. return
  2073. # Read-only memberships cost no API call, mirroring the posted path.
  2074. if not self._answers_in_room(payload.room_id):
  2075. logger.debug("Chatto: edit from read-only room %s ignored", payload.room_id)
  2076. return
  2077. client = await self._get_chatto_client()
  2078. if client is None:
  2079. logger.warning("Chatto: dropping edit - no client available")
  2080. return
  2081. logger.debug("Chatto WS: 'message_edited' payload:%s", payload)
  2082. message = await client.get_message(
  2083. room_id=payload.room_id, event_id=payload.message_event_id
  2084. )
  2085. if message is None or message.deleted_at:
  2086. return
  2087. message_body = message.body or ""
  2088. if not message_body and not message.attachments:
  2089. return
  2090. if not self._edit_is_fresh(message):
  2091. logger.debug(
  2092. "Chatto: edit of msg %s outside the edit window",
  2093. payload.message_event_id,
  2094. )
  2095. return
  2096. # Cheap triage before the admission pipeline: an edit to an
  2097. # already-settled message (dispatched, neither running nor queued)
  2098. # must not cost get_room/media calls or re-fire acknowledgements.
  2099. was_dispatched = payload.message_event_id in self._dispatched_ids
  2100. if (
  2101. was_dispatched
  2102. and payload.message_event_id not in self._processing.values()
  2103. and not any(
  2104. pending.message_id == payload.message_event_id
  2105. for pending in self._pending_messages.values()
  2106. )
  2107. ):
  2108. logger.debug(
  2109. "Chatto: edit of already-answered msg %s ignored",
  2110. payload.message_event_id,
  2111. )
  2112. return
  2113. event = await self._admit_and_build(
  2114. client,
  2115. room_id=payload.room_id,
  2116. message=message,
  2117. source_message_id=payload.message_event_id,
  2118. thread_root_event_id=message.thread_root_event_id or None,
  2119. allow_dm_commands=False,
  2120. )
  2121. if event is None:
  2122. return
  2123. session_key = self._session_key_for(event.source)
  2124. if self._processing.get(session_key) == payload.message_event_id:
  2125. logger.info(
  2126. "Chatto: msg %s edited mid-run - restarting the turn",
  2127. payload.message_event_id,
  2128. )
  2129. # The cancelled task's completion hook clears _processing and
  2130. # reports 🚫 before this coroutine moves on, because cancel
  2131. # awaits the task. Queued follow-ups must survive.
  2132. await self.cancel_session_processing(
  2133. session_key, release_guard=True, discard_pending=False
  2134. )
  2135. elif not was_dispatched:
  2136. logger.info(
  2137. "Chatto: msg %s was never dispatched - edit starts a fresh turn",
  2138. payload.message_event_id,
  2139. )
  2140. else:
  2141. pending = self._pending_messages.get(session_key)
  2142. if pending is not None and pending.message_id == payload.message_event_id:
  2143. # Still queued behind the running turn: correct it in place
  2144. # instead of answering stale wording later.
  2145. pending.text = event.text
  2146. logger.info(
  2147. "Chatto: queued msg %s updated to its edited text",
  2148. payload.message_event_id,
  2149. )
  2150. return
  2151. logger.debug(
  2152. "Chatto: edit of already-answered msg %s ignored",
  2153. payload.message_event_id,
  2154. )
  2155. return
  2156. self._remember_dispatched(event.message_id or "")
  2157. logger.info("Chatto: dispatching edited message to Hermes")
  2158. await self.handle_message(event)
  2159. async def _admit_and_build(
  2160. self,
  2161. client: ChattoClient,
  2162. *,
  2163. room_id: str,
  2164. message: Message,
  2165. source_message_id: str,
  2166. thread_root_event_id: str | None,
  2167. mentions: _Mentions | None = None,
  2168. allow_dm_commands: bool = True,
  2169. ) -> MessageEvent | None:
  2170. """Run one hydrated inbound message through the admission pipeline.
  2171. Shared by the posted and the edited path: user resolution, auth,
  2172. mention gates, thread anchoring and media caching all behave
  2173. identically for both. Returns ``None`` for anything that must not
  2174. reach the agent. DM membership commands are executed here (side
  2175. effect) unless ``allow_dm_commands`` is False — edits pass False so
  2176. a corrected command line neither runs twice nor leaks to the agent.
  2177. A dispatch that opens a channel thread additionally carries the
  2178. member roster in ``channel_context`` (side effect: once the roster
  2179. was fetched, the thread root is recorded as announced).
  2180. ``mentions`` is the already-resolved answer to "who does this
  2181. address"; passing None derives it from the message body instead, which
  2182. is what an edit does because its event carries no targets. The
  2183. derivation happens down here rather than at the call site because
  2184. resolving a handle needs the member cache, and the roster fetch below
  2185. is what fills it — read any earlier, every handle looks unknown.
  2186. The caller owns dispatching: a non-None result still needs
  2187. ``handle_message()``.
  2188. """
  2189. user = self._user_cache.get(message.actor_id)
  2190. if user is None:
  2191. logger.debug("Chatto: resolving user %s", message.actor_id)
  2192. member = await client.get_room_member(
  2193. room_id=message.room_id, user_id=message.actor_id
  2194. )
  2195. if member is None or member.user is None:
  2196. logger.debug(
  2197. "Chatto: dropping message from unknown user %s",
  2198. message.actor_id,
  2199. )
  2200. return None
  2201. user = member.user
  2202. self._user_cache[user.id] = user
  2203. if not self._check_auth(user):
  2204. logger.debug(
  2205. "Chatto: dropping message from user %s (auth denied)",
  2206. message.actor_id,
  2207. )
  2208. return None
  2209. room_kind = await self._room_kind_for(client, message.room_id)
  2210. if room_kind is None:
  2211. logger.debug(
  2212. "Chatto: dropping message from room %s (room_kind lookup failed)",
  2213. message.room_id,
  2214. )
  2215. return None
  2216. message_body = message.body or ""
  2217. logger.debug("message_body: %s room_kind: %s", message_body, room_kind)
  2218. # Membership commands ride in over DMs only: they change what the bot
  2219. # listens to and must never reach the agent pipeline or the mention
  2220. # gates.
  2221. if room_kind == RoomKind.DM:
  2222. if allow_dm_commands:
  2223. if await self._handle_dm_command(room_id, message_body):
  2224. return None
  2225. elif message_body.startswith("/"):
  2226. logger.debug("Chatto: edited DM command %r not re-run", message_body)
  2227. return None
  2228. # Mention gating deliberately covers everything but DMs: in a channel
  2229. # the bot is one of many listeners and must be addressed, whereas a DM
  2230. # is already addressed at it. Chatto has no group rooms — any
  2231. # multi-participant surface is a channel, and a room whose kind the
  2232. # server never set counts as one too (see _answers_in_room). Both gates
  2233. # read one resolved `mentions`, so "addressed" is defined once and
  2234. # broadcast/role targets count for us on either path.
  2235. if room_kind != RoomKind.DM:
  2236. policy = self._room_policy(room_id)
  2237. # Handle resolution on the body-derived path reads the member
  2238. # cache, which the roster projection fills. Fetch it before deriving
  2239. # anything, or every handle looks unknown — the same projection is
  2240. # then reused for this turn's channel_context further down, one
  2241. # fetch per room.
  2242. if policy == RoomPolicy.OPEN:
  2243. await self._roster_for_room(client, room_id=room_id)
  2244. if mentions is None:
  2245. mentions = self._mentions_from_body(message_body)
  2246. if room_kind != RoomKind.DM:
  2247. policy = self._room_policy(room_id)
  2248. if policy == RoomPolicy.REQUIRE_MENTION and not mentions.me:
  2249. logger.debug(
  2250. "Chatto: dropping unaddressed message from %s (policy %s)",
  2251. room_id,
  2252. policy.value,
  2253. )
  2254. return None
  2255. # In an open channel we see every message, including ones plainly
  2256. # aimed at a named colleague. Answering those would be barging in,
  2257. # so acknowledge that we read it and stay quiet. Checked after the
  2258. # bot-mention test above, so a message naming us *and* someone
  2259. # else still counts as ours.
  2260. if policy == RoomPolicy.OPEN and not mentions.me and mentions.someone_else:
  2261. logger.info(
  2262. "Chatto: message addresses someone else, acknowledging only"
  2263. )
  2264. if self.chatto_config.reactions.value:
  2265. await self.add_reaction(message.room_id, message.id, "🫥")
  2266. return None
  2267. # Thread anchoring — if the incoming message is inside a Chatto thread, we
  2268. # keep that thread by default; otherwise leave thread_id unset so
  2269. # replies land at the root.
  2270. thread_id = (
  2271. thread_root_event_id or None
  2272. ) # we could also take the room id but then, we're in a thread already.
  2273. if not thread_id and room_kind != RoomKind.DM:
  2274. thread_id = message.id
  2275. logger.debug(
  2276. "Chatto: thread anchoring for msg %s: incoming thread_root_event_id=%r, "
  2277. "room_kind=%s, anchored thread_id=%r",
  2278. message.id,
  2279. message.thread_root_event_id,
  2280. room_kind.name,
  2281. thread_id,
  2282. )
  2283. # Every channel turn carries the room's roster: threads hold isolated
  2284. # sessions and the agent only sees channel_context per dispatch, so a
  2285. # repeat is not deduplication but the point (see _roster_for_room).
  2286. # The gateway prepends channel_context above the message text, so the
  2287. # roster never mingles with what the user actually wrote.
  2288. source = self.build_source(
  2289. chat_id=room_id,
  2290. chat_name=self._room_names.get(message.room_id),
  2291. chat_type=chat_type_for_room_kind(room_kind),
  2292. user_id=message.actor_id,
  2293. user_name=user.login, # use login, because display_name is changeable by anyone.
  2294. thread_id=thread_id,
  2295. message_id=source_message_id,
  2296. role_authorized=True,
  2297. )
  2298. # Channel context rides ahead of the message text as read-only
  2299. # reference: the roster names the audience, the thread block carries
  2300. # what the thread already said. DMs get neither — there is no audience
  2301. # to name and no thread to catch up on. Built after the source, because
  2302. # the thread block asks the session store whether this thread's session
  2303. # already has the history (see _thread_context_for).
  2304. context_blocks: list[str] = []
  2305. if room_kind != RoomKind.DM:
  2306. logger.debug(
  2307. "Chatto: fetching roster for room %s",
  2308. room_id,
  2309. )
  2310. roster = await self._roster_for_room(client, room_id=room_id)
  2311. if roster:
  2312. context_blocks.append(roster)
  2313. else:
  2314. logger.debug(
  2315. "Chatto: dispatching channel message without roster "
  2316. "(lookup failed or empty)"
  2317. )
  2318. thread_context = await self._thread_context_for(
  2319. client,
  2320. room_id=room_id,
  2321. thread_root_event_id=thread_root_event_id or "",
  2322. current_message_id=message.id,
  2323. source=source,
  2324. )
  2325. if thread_context:
  2326. context_blocks.append(thread_context)
  2327. # A fresh room message roots its own session (the anchoring above),
  2328. # so it starts empty even when the room talked for hours. The reply
  2329. # pointer above carries what this message answers; this block adds
  2330. # what the room said before it — including the bot's own output,
  2331. # whose echo is filtered as a self-event and reaches no session
  2332. # any other way.
  2333. if not thread_root_event_id:
  2334. room_context = await self._room_context_for(
  2335. client,
  2336. room_id=room_id,
  2337. trigger=message,
  2338. source=source,
  2339. )
  2340. if room_context:
  2341. context_blocks.append(room_context)
  2342. # A reply must not read as a fresh conversation: the gateway renders
  2343. # ``reply_to_text`` into the turn as "[Replying to …]", but only when the
  2344. # adapter resolved it. Signal does this for quotes; a Chatto reply's
  2345. # target is one get_message away, so a session that starts here (every
  2346. # fresh room message roots its own — see the anchoring above) at least
  2347. # knows what the reply answers. DMs get the same treatment: a reply is
  2348. # the one pointer a session start can carry there too.
  2349. reply_to_text: str | None = None
  2350. reply_to_is_own = False
  2351. if message.in_reply_to:
  2352. target = await self._reply_target(client, room_id, message.in_reply_to)
  2353. if target is not None:
  2354. reply_to_text = target.body or ""
  2355. reply_to_is_own = self._is_own(target)
  2356. # prepare a MessageEvent
  2357. message_event = MessageEvent(
  2358. text=message_body,
  2359. source=source,
  2360. message_id=message.id,
  2361. timestamp=message.created_at or datetime.now(UTC),
  2362. raw_message=message,
  2363. reply_to_message_id=message.in_reply_to,
  2364. reply_to_text=reply_to_text,
  2365. reply_to_is_own_message=reply_to_is_own,
  2366. channel_context="\n\n".join(context_blocks) or None,
  2367. )
  2368. if message_event.is_command():
  2369. message_event.message_type = MessageType.COMMAND
  2370. # Attachments — download and hand the local cache paths to the gateway,
  2371. # which runs vision enrichment / document extraction off media_urls.
  2372. (
  2373. message_event.media_urls,
  2374. message_event.media_types,
  2375. media_kinds,
  2376. ) = await self._cache_attachments(list(message.attachments))
  2377. if media_kinds:
  2378. # Same precedence as the Teams/Signal adapters: document-context
  2379. # injection gates strictly on DOCUMENT, image handling keys off the
  2380. # per-path image/* MIME regardless of message_type.
  2381. message_event.message_type = self._message_type_for_media_kinds(media_kinds)
  2382. else:
  2383. message_event.message_type = MessageType.TEXT
  2384. logger.debug("Chatto: MessageEvent: %s", message_event)
  2385. return message_event
  2386. async def _forward_reaction(
  2387. self,
  2388. event: RealtimeEvent,
  2389. payload: Any,
  2390. *,
  2391. removed: bool,
  2392. ) -> None:
  2393. """Forward a human reaction to the gateway's reaction hook surface.
  2394. The handler is registered by the gateway via ``set_reaction_handler``
  2395. and fans out as ``reaction:added`` / ``reaction:removed`` through the
  2396. HookRegistry. The dict shape mirrors the Slack adapter's — hook
  2397. consumers are written against that contract, not against a per-platform
  2398. one. Our own lifecycle reactions (👀/✅/❌) are dropped: forwarding them
  2399. would feed the agent its own markers.
  2400. """
  2401. actor_id = event.actor_id
  2402. if actor_id and self.me and actor_id == self.me.id:
  2403. return
  2404. if not payload.room_id or not payload.message_event_id or not actor_id:
  2405. return
  2406. handler = self._reaction_handler
  2407. if handler is None:
  2408. return
  2409. # The server echoes the shortcode name back in the event ("thumbsup",
  2410. # "white_check_mark") — which is exactly the shape the mirrored Slack
  2411. # contract uses (Slack reaction events carry names too), so it is
  2412. # forwarded as-is rather than decoded.
  2413. action = "removed" if removed else "added"
  2414. try:
  2415. await handler(
  2416. {
  2417. "platform": ChattoConstants.PLATFORM_NAME,
  2418. "event_name": f"reaction:{action}",
  2419. "reaction": payload.emoji,
  2420. "user_id": actor_id,
  2421. "item_user_id": None,
  2422. "item_type": "message",
  2423. "channel_id": payload.room_id,
  2424. "message_ts": payload.message_event_id,
  2425. "event_ts": event.id,
  2426. "raw_event": event,
  2427. },
  2428. )
  2429. except Exception: # pragma: no cover - the hook contract is non-blocking
  2430. logger.debug("Chatto: reaction hook forwarding failed", exc_info=True)
  2431. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  2432. if self._is_seen(event.id):
  2433. return
  2434. if event.actor_id is None:
  2435. return
  2436. logger.debug("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  2437. # Self-event filter — the actor_id on the envelope is authoritative.
  2438. actor_id = event.actor_id
  2439. if actor_id and self.me and actor_id == self.me.id:
  2440. return
  2441. if event.kind == "message_posted":
  2442. await self._dispatch_message_posted(event.payload, event.id)
  2443. elif event.kind == "message_edited":
  2444. await self._dispatch_message_edited(event.payload)
  2445. elif event.kind in ("reaction_added", "reaction_removed"):
  2446. # Interactive prompts (clarify / exec-approval) are driven by
  2447. # reactions. Route a reaction on a tracked prompt before
  2448. # forwarding — the prompt is consumed either way, but the reaction
  2449. # still reaches the gateway hook surface afterward.
  2450. if event.kind == "reaction_added":
  2451. try:
  2452. await self._try_handle_interactive_reaction(
  2453. getattr(event.payload, "room_id", None),
  2454. getattr(event.payload, "message_event_id", None),
  2455. getattr(event.payload, "emoji", None),
  2456. actor_id,
  2457. )
  2458. except Exception:
  2459. logger.debug(
  2460. "Chatto: interactive reaction routing failed", exc_info=True
  2461. )
  2462. await self._forward_reaction(
  2463. event,
  2464. event.payload,
  2465. removed=event.kind == "reaction_removed",
  2466. )
  2467. elif event.kind == "presence_changed":
  2468. # A participant's presence changed — patch the cached user in place.
  2469. # The identified user is the event's own actor: the realtime
  2470. # PresenceChangedEvent carries only a status field, and a
  2471. # payload.user_id read here raised AttributeError on every
  2472. # presence change, which the event loop mistook for a broken
  2473. # stream and answered with a reconnect backoff — dropping
  2474. # inbound messages that arrived inside the gap.
  2475. changed_user_id = event.actor_id
  2476. if (
  2477. changed_user_id
  2478. and (user := self._user_cache.get(changed_user_id)) is not None
  2479. ):
  2480. # The realtime payload carries the proto enum as a plain int
  2481. # (protobuf runtime without native enum wrappers); chattolib's
  2482. # own bot.py coerces the same field the same way. Read the
  2483. # wire shape, never ``.name`` directly, which raised
  2484. # AttributeError on every presence change and dropped inbound
  2485. # messages inside the reconnect gaps that followed.
  2486. raw_status = event.payload.status
  2487. if isinstance(raw_status, PresenceStatus):
  2488. status = raw_status
  2489. else:
  2490. proto_name = ProtoPresenceStatus.Name(int(raw_status))
  2491. status = _PRESENCE_BY_PROTO_NAME.get(
  2492. proto_name, PresenceStatus.UNSPECIFIED
  2493. )
  2494. user.presence_status = status
  2495. logger.debug(
  2496. "Chatto: patched presence of %s to %s",
  2497. changed_user_id,
  2498. status.name,
  2499. )
  2500. elif event.kind in ("user_joined_room", "user_left_room"):
  2501. # Membership moved — the room's roster projection is now wrong, so
  2502. # discard it; the next turn there refetches once and re-delivers.
  2503. if event.payload.room_id in self._roster_announced:
  2504. logger.debug(
  2505. "Chatto: %s invalidated the roster of room %s",
  2506. event.kind,
  2507. event.payload.room_id,
  2508. )
  2509. self._evict_roster(event.payload.room_id)
  2510. elif event.kind == "room_updated":
  2511. # Room metadata changed (name, description) — patch the cache in
  2512. # place so the next turn sees the fresh values instead of stale
  2513. # names from a long-lived _room_names dict.
  2514. payload = event.payload
  2515. room_id = getattr(payload, "room_id", None)
  2516. if room_id and room_id in self._joined_room_ids:
  2517. name = getattr(payload, "name", None)
  2518. if name is not None:
  2519. self._room_names[room_id] = name
  2520. logger.debug(
  2521. "Chatto: room %s updated: name=%s",
  2522. room_id,
  2523. name,
  2524. )
  2525. elif event.kind == "room_groups_updated":
  2526. # Room-group membership moved — discard the cached projection so
  2527. # the next turn that needs room groups refetches once.
  2528. logger.debug("Chatto: room_groups_updated — discarding cached group state")
  2529. elif event.kind == "message_retracted":
  2530. # A message was retracted — no-op for now. Interactive prompts
  2531. # are keyed by their own message IDs (not the original event_id),
  2532. # and the prompt timeout handles stale cards anyway.
  2533. payload = event.payload
  2534. logger.debug(
  2535. "Chatto: message retracted: %s in %s",
  2536. getattr(payload, "message_event_id", None),
  2537. getattr(payload, "room_id", None),
  2538. )
  2539. elif event.kind == "thread_created":
  2540. # A human created a thread — no adapter action needed. The thread
  2541. # will be seeded on first message because _seeded_threads starts
  2542. # empty and seeds on first turn into an unknown root.
  2543. payload = event.payload
  2544. logger.debug(
  2545. "Chatto: thread created: room=%s root=%s",
  2546. getattr(payload, "room_id", None),
  2547. getattr(payload, "thread_root_event_id", None),
  2548. )
  2549. elif event.kind == "user_typing":
  2550. # Presence-like ephemeral signal: a user is typing in a room.
  2551. # The adapter never surfaces this to the agent — it is only useful
  2552. # for a client UI cursor, which is not what a bot does.
  2553. logger.debug("Chatto: user_typing event received")
  2554. # confirmed:
  2555. # NOTE: "projection_event" (and "caught_up") belong to realtime protocol
  2556. # v2 on unreleased Chatto main — chattolib speaks v1 and can never
  2557. # deliver them here. Revisit when vendored chattolib gains v2 typing.
  2558. # The notification_* / viewer-state kinds are the server's per-viewer
  2559. # bookkeeping: they fire on every read-state change in every followed
  2560. # room, need no adapter action, and warning on each one buried real
  2561. # signals in noise.
  2562. elif event.kind in (
  2563. "mention_notification",
  2564. "notification_dismissed",
  2565. "notification_occurrences_changed",
  2566. "notification_unread_state_changed",
  2567. "thread_viewer_state_changed",
  2568. "room_marked_as_read",
  2569. "user_typing",
  2570. "notification_created",
  2571. "new_direct_message_notification",
  2572. "message_retracted",
  2573. "thread_created",
  2574. "thread_follow_changed",
  2575. ):
  2576. logger.debug(
  2577. "Chatto: '%s' event received. Not yet implemented or not needed.",
  2578. event.kind,
  2579. )
  2580. else:
  2581. logger.warning("Chatto: unknown event kind: '%s'", event.kind)
  2582. async def _chattolib_event_loop(self) -> None:
  2583. """Event loop using chattolib's stream_events.
  2584. This replaces the manual WebSocket loop with chattolib's high-level
  2585. stream_events() which provides pre-decoded RealtimeEvent objects.
  2586. """
  2587. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  2588. while not self._closing:
  2589. try:
  2590. client = await self._require_chatto_client()
  2591. await self._refresh_rooms()
  2592. logger.info(
  2593. "Chatto: starting chattolib event stream with %d rooms",
  2594. len(self._joined_room_ids),
  2595. )
  2596. async for event in stream_events(
  2597. client, resume_cursor=self._realtime_cursor
  2598. ):
  2599. if self._closing:
  2600. return
  2601. if isinstance(event, RealtimeEvent):
  2602. try:
  2603. await self._handle_realtime_event(event)
  2604. except (AttributeError, TypeError) as exc:
  2605. # A handler reading a payload field that does not
  2606. # exist or is not the type it assumed is a handler
  2607. # bug, not wire damage: it failed one event, so it
  2608. # must not cost the stream. Reconnecting here is
  2609. # what turned the presence crashes into 30s
  2610. # backoff gaps that silently dropped every
  2611. # message_posted arriving inside them (see
  2612. # AGENTS.md, "A handler bug is not a broken
  2613. # stream"). The cursor is NOT advanced: an event
  2614. # the adapter never applied is not safe to resume
  2615. # past.
  2616. logger.warning(
  2617. "Chatto: handler for '%s' failed (%s); skipping event %s",
  2618. event.kind,
  2619. exc,
  2620. event.id,
  2621. )
  2622. except Exception:
  2623. # Not a wire-shape bug — loud traceback, same skip
  2624. # semantics: one event failed, the stream stays up.
  2625. logger.exception(
  2626. "Chatto: handler for '%s' crashed on event %s; skipping it",
  2627. event.kind,
  2628. event.id,
  2629. )
  2630. else:
  2631. # chattolib marks a cursor as safe only once its event
  2632. # has been applied, and leaves it None when the event
  2633. # cannot be replayed. Keeping the last good one is what
  2634. # turns a reconnect into a resume rather than a gap.
  2635. if event.cursor:
  2636. self._realtime_cursor = event.cursor
  2637. # Iterator exited cleanly — treat as a normal close and reconnect
  2638. # with the local backoff (no server hint available).
  2639. logger.info("Chatto: realtime stream ended, reconnecting")
  2640. except asyncio.CancelledError:
  2641. return
  2642. except ChattoRealtimeCloseError as exc:
  2643. if not exc.reconnect:
  2644. logger.error(
  2645. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  2646. exc.code,
  2647. exc.message,
  2648. )
  2649. return
  2650. wait = max(
  2651. exc.retry_after_ms / 1000.0,
  2652. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF,
  2653. )
  2654. logger.warning(
  2655. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  2656. exc.code,
  2657. wait,
  2658. )
  2659. delay = (
  2660. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  2661. ) # server hint supersedes local backoff
  2662. await self._sleep_interruptible(wait)
  2663. continue
  2664. except ChattoRealtimeError as exc:
  2665. if exc.fatal:
  2666. logger.error(
  2667. "Chatto: fatal realtime error (%s): %s", exc.code, exc.message
  2668. )
  2669. return
  2670. logger.warning(
  2671. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  2672. exc.code,
  2673. exc.message,
  2674. delay,
  2675. )
  2676. except Exception as exc:
  2677. cause = exc.__cause__
  2678. if cause is not None and isinstance(cause, TypeError):
  2679. logger.warning(
  2680. "Chatto: realtime wire corruption (%s), reconnecting in %.1fs",
  2681. cause,
  2682. delay,
  2683. )
  2684. else:
  2685. logger.warning(
  2686. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  2687. exc,
  2688. delay,
  2689. )
  2690. if self._closing:
  2691. return
  2692. jitter = delay * 0.2 * random.random()
  2693. await self._sleep_interruptible(delay + jitter)
  2694. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  2695. async def _sleep_interruptible(self, seconds: float) -> None:
  2696. """Sleep in short slices so disconnect() cancels promptly."""
  2697. end = asyncio.get_running_loop().time() + seconds
  2698. while not self._closing:
  2699. remaining = end - asyncio.get_running_loop().time()
  2700. if remaining <= 0:
  2701. return
  2702. await asyncio.sleep(min(remaining, 0.5))
  2703. def _warn_if_home_channel_unjoined(self, member_ids: set[str]) -> None:
  2704. """Warn once when CHATTO_HOME_CHANNEL names a room the bot is not in.
  2705. Standalone cron delivery posts straight into that room with a fresh
  2706. client and no join logic of its own — without server-side membership
  2707. every proactive send fails there.
  2708. """
  2709. home_id = (self.chatto_config.home_channel.value or "").strip()
  2710. if (
  2711. not home_id
  2712. or home_id in member_ids
  2713. or home_id in self._joined_room_ids
  2714. or self._home_warning_logged
  2715. ):
  2716. return
  2717. self._home_warning_logged = True
  2718. logger.warning(
  2719. "Chatto: CHATTO_HOME_CHANNEL '%s' is not a joined room - cron and "
  2720. "notification delivery will fail until the bot joins it (invite "
  2721. "the account natively in Chatto, or DM it '/join').",
  2722. home_id,
  2723. )
  2724. async def _resolve_dm_partner(self, client: ChattoClient, room_id: str) -> None:
  2725. """Cache the chat partner's login for a DM room, best-effort.
  2726. DM rooms carry no usable name of their own, so the joined-rooms
  2727. summary names the other side instead. Resolved once per room and
  2728. session; without our own user (pre-connect) or on a directory error
  2729. the raw room name stays in place.
  2730. """
  2731. if room_id in self._dm_partners or self.me is None:
  2732. return
  2733. try:
  2734. member_ids, _page = await client.list_room_members(room_id)
  2735. if not member_ids:
  2736. return
  2737. members = await client.batch_get_room_members(room_id, member_ids)
  2738. except Exception:
  2739. logger.debug(
  2740. "Chatto: could not list members of DM %s", room_id, exc_info=True
  2741. )
  2742. return
  2743. for member in members:
  2744. user = member.user
  2745. if user and user.id != self.me.id:
  2746. self._dm_partners[room_id] = user.login or user.display_name
  2747. return
  2748. def _joined_room_label(self, room_id: str) -> str:
  2749. """One entry for the joined-rooms summary, with how-we-answer tags.
  2750. The tag names the room's participation mode at a glance: DMs answer
  2751. unconditionally, listed channels answer on mentions or every message,
  2752. and an unlisted channel is read-only. A DM is labelled with its chat
  2753. partner's login rather than its (empty) room name, and names are
  2754. quoted so empty strings and spaces stay visible.
  2755. """
  2756. name = self._room_names.get(room_id, room_id)
  2757. if self._room_kinds.get(room_id) == RoomKind.DM:
  2758. tags = "[dm]"
  2759. name = self._dm_partners.get(room_id) or name
  2760. else:
  2761. policy = self._room_policy(room_id)
  2762. if policy == RoomPolicy.REQUIRE_MENTION:
  2763. tags = "[on-mention]"
  2764. elif policy == RoomPolicy.OPEN:
  2765. tags = "[every-message]"
  2766. else:
  2767. tags = "[read-only]"
  2768. if room_id in self._universal_room_ids:
  2769. tags += " [universal]"
  2770. return f'"{name}" ({room_id}) {tags}'
  2771. def _log_joined_rooms(self) -> None:
  2772. """Log the joined rooms and how the bot answers in each of them."""
  2773. labels = [self._joined_room_label(rid) for rid in self._joined_room_ids]
  2774. logger.info(
  2775. "Chatto WS: currently joined in %d room(s): %s",
  2776. len(labels),
  2777. ", ".join(labels),
  2778. )
  2779. async def _refresh_rooms(self) -> None:
  2780. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms.
  2781. Runs once per (re)connect, so this is also the bootstrap point for the
  2782. roster projection: nothing on the wire reports presence at connect
  2783. time (the subscribe snapshot has no presence field; presence arrives
  2784. as its own events), so cached presence could only heal on the next
  2785. random change. Discarding it makes each announced room's first turn
  2786. refetch fresh data — lazily, so quiet rooms stay free of API calls.
  2787. """
  2788. client = await self._get_chatto_client()
  2789. if client is None:
  2790. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  2791. return
  2792. for announced in list(self._roster_announced):
  2793. self._evict_roster(announced)
  2794. try:
  2795. rooms_list = await client.list_rooms()
  2796. member_ids: set[str] = set()
  2797. new_room_ids: list[str] = []
  2798. for room_with_state in rooms_list:
  2799. if not room_with_state:
  2800. continue
  2801. room_obj = room_with_state.room or None
  2802. if not room_obj:
  2803. continue
  2804. self._room_names[room_obj.id] = room_obj.name
  2805. self._room_kinds[room_obj.id] = room_obj.kind
  2806. if room_obj.kind == RoomKind.DM:
  2807. await self._resolve_dm_partner(client, room_obj.id)
  2808. if room_obj.universal:
  2809. self._universal_room_ids.add(room_obj.id)
  2810. if not room_with_state.viewer_state.is_member:
  2811. continue
  2812. member_ids.add(room_obj.id)
  2813. if room_obj.id not in self._joined_room_ids:
  2814. new_room_ids.append(room_obj.id)
  2815. # Left via /leave, kicked, deleted: rooms we no longer belong
  2816. # to drop out here — otherwise the next refresh would quietly
  2817. # re-add what /leave just removed.
  2818. stale_room_ids = [
  2819. rid for rid in self._joined_room_ids if rid not in member_ids
  2820. ]
  2821. for rid in stale_room_ids:
  2822. self._joined_room_ids.remove(rid)
  2823. self._evict_roster(rid)
  2824. if stale_room_ids:
  2825. logger.info(
  2826. "Chatto WS: no longer a member of %d room(s): %s",
  2827. len(stale_room_ids),
  2828. stale_room_ids,
  2829. )
  2830. self._warn_if_home_channel_unjoined(member_ids)
  2831. if new_room_ids:
  2832. logger.info(
  2833. "Chatto WS: discovered %d new room(s): %s",
  2834. len(new_room_ids),
  2835. new_room_ids,
  2836. )
  2837. for rid in new_room_ids:
  2838. # Membership came straight from the directory scan
  2839. # (viewer_state.is_member); natively invited rooms need no
  2840. # JoinRoom call — same rule as _run_join.
  2841. if self._answers_in_room(rid):
  2842. await self._seed_room(rid)
  2843. else:
  2844. logger.info(
  2845. "Chatto WS: %s (%s) is on neither mention list -"
  2846. " joined read-only",
  2847. self._room_names.get(rid, rid),
  2848. rid,
  2849. )
  2850. self._joined_room_ids.append(rid)
  2851. self._log_joined_rooms()
  2852. except Exception:
  2853. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  2854. # ------------------------------------------------------------------ #
  2855. # Read state (best-effort, Chatto-unique)
  2856. # ------------------------------------------------------------------ #
  2857. # Deliberately outside the try block above: this sweep runs on every
  2858. # refresh — including refreshes that discovered no new rooms. The
  2859. # old early return starved it to "only when something changed",
  2860. # leaving silent rooms unmarked for whole connection lifetimes.
  2861. # Best-effort: mark all joined rooms as read (room_id may be undefined here)
  2862. for _rid in list(self._joined_room_ids):
  2863. try:
  2864. await client.mark_room_as_read(room_id=_rid)
  2865. except Exception:
  2866. logger.debug(
  2867. "Chatto: mark_room_as_read failed for %s", _rid, exc_info=True
  2868. )
  2869. # ------------------------------------------------------------------ #
  2870. # Sending (ConnectRPC — unchanged from polling version)
  2871. # ------------------------------------------------------------------ #
  2872. def _resolve_outbound_thread(
  2873. self,
  2874. chat_id: str,
  2875. reply_to: str | None,
  2876. metadata: dict[str, Any] | None,
  2877. ) -> str | None:
  2878. """The thread an outbound message belongs in, or ``None`` for the room.
  2879. One definition for every outbound path (text and attachments):
  2880. ``metadata["thread_id"]`` wins — it names the thread root to stay in;
  2881. otherwise ``reply_to`` anchors a thread under the incoming message,
  2882. but only with ``auto_thread`` enabled. DMs never thread.
  2883. Deliberately does NOT open an auto-thread of its own — only the
  2884. chunked text path in :meth:`send` does that, because only there do
  2885. further chunks follow into the freshly created thread.
  2886. """
  2887. thread_id = (metadata or {}).get("thread_id")
  2888. if reply_to and self.chatto_config.auto_thread.value and not thread_id:
  2889. thread_id = reply_to
  2890. if self._room_kinds.get(chat_id) == RoomKind.DM:
  2891. return None
  2892. return str(thread_id) if thread_id else None
  2893. async def send(
  2894. self,
  2895. chat_id: str,
  2896. content: str,
  2897. reply_to: str | None = None,
  2898. metadata: dict[str, Any] | None = None,
  2899. ) -> SendResult:
  2900. """Send a message to a Chatto room.
  2901. Long messages are split into chunks via ``truncate_message`` and
  2902. each chunk is sent as a separate CreateMessage call. The first
  2903. chunk's message ID is returned as ``message_id``.
  2904. When ``auto_thread`` is enabled and the incoming message was a
  2905. regular room message (not already in a thread), the first chunk is
  2906. sent as a room message and its ID becomes the thread root. Subsequent
  2907. chunks are sent in that thread. This mirrors Discord's auto_thread
  2908. behavior.
  2909. BasePlatformAdapter override
  2910. """
  2911. if not content:
  2912. return SendResult(success=False, error="Empty message")
  2913. thread_id = self._resolve_outbound_thread(chat_id, reply_to, metadata)
  2914. room_kind = self._room_kinds.get(chat_id)
  2915. is_dm = room_kind == RoomKind.DM
  2916. # Auto-thread: by default, Chatto creates a thread for replies to room
  2917. # messages (not DMs, not already in a thread). This keeps conversations
  2918. # organized in the room. Can be disabled via extra.auto_thread=false.
  2919. use_auto_thread = (
  2920. self.chatto_config.auto_thread.value and not thread_id and not is_dm
  2921. )
  2922. client = await self._get_chatto_client()
  2923. if client is None:
  2924. return SendResult(
  2925. success=False, error="Chatto client not available", retryable=True
  2926. )
  2927. # The split, the routing and the stop-at-first-failure all live in
  2928. # _deliver_chunks, shared with the plugin tools: a long answer must
  2929. # reach the room the same way whoever sent it.
  2930. delivery = await _deliver_chunks(
  2931. client,
  2932. chat_id,
  2933. content,
  2934. thread_root_event_id=str(thread_id) if thread_id else "",
  2935. create_thread=use_auto_thread,
  2936. on_posted=self._mark_seen,
  2937. )
  2938. message_ids = delivery.message_ids
  2939. if use_auto_thread and message_ids and not thread_id:
  2940. thread_id = delivery.root_event_id
  2941. # Nothing got through at all — report the failure instead of a phantom success.
  2942. if not message_ids:
  2943. # Only server-side failures count as retryable; a bug in our own
  2944. # code must not read as a transient network blip.
  2945. return SendResult(
  2946. success=False,
  2947. error=(
  2948. str(delivery.error)
  2949. if delivery.error
  2950. else "Chatto: message could not be sent"
  2951. ),
  2952. retryable=isinstance(delivery.error, ChattoError),
  2953. )
  2954. first_id = message_ids[0]
  2955. # ------------------------------------------------------------------ #
  2956. # Thread following (best-effort, Chatto-unique)
  2957. # ------------------------------------------------------------------ #
  2958. if thread_id:
  2959. try:
  2960. await client.follow_thread(chat_id, thread_id)
  2961. except Exception:
  2962. logger.debug(
  2963. "Chatto: follow_thread failed for %s/%s",
  2964. chat_id,
  2965. thread_id,
  2966. exc_info=True,
  2967. )
  2968. # A later chunk failed after earlier ones went out: partial delivery.
  2969. if delivery.error is not None:
  2970. logger.warning(
  2971. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  2972. len(message_ids),
  2973. delivery.chunks_total,
  2974. chat_id,
  2975. delivery.error,
  2976. )
  2977. # raw_response stays unset (dict-shaped per the SendResult contract):
  2978. # gateway consumers such as the cron scheduler call .get() on it, so a
  2979. # chattolib Message here would crash delivery bookkeeping *after* the
  2980. # send already succeeded — the job then falls back to the standalone
  2981. # path and the room sees the message twice.
  2982. return SendResult(success=True, message_id=first_id)
  2983. def format_message(self, content: str) -> str:
  2984. """Normalise outgoing text for Chatto.
  2985. The transformations live in :func:`_normalise_outbound_text`, shared
  2986. with the standalone cron sender.
  2987. BasePlatformAdapter override
  2988. """
  2989. return _normalise_outbound_text(content)
  2990. async def send_clarify(
  2991. self,
  2992. chat_id: str,
  2993. question: str,
  2994. choices: list[str] | None,
  2995. clarify_id: str,
  2996. session_key: str,
  2997. metadata: dict[str, Any] | None = None,
  2998. ) -> SendResult:
  2999. """Post a reaction-driven clarify prompt.
  3000. When ``choices`` is empty/None or exceeds 9 entries (the number emojis
  3001. only cover 1-9), delegate to the base-class text fallback. Otherwise
  3002. post a numbered message, seed one reaction per option plus ``✏️``
  3003. (Other), register the prompt in both registries, and return.
  3004. BasePlatformAdapter override
  3005. """
  3006. if not choices or len(choices) > 9:
  3007. return await super().send_clarify(
  3008. chat_id, question, choices, clarify_id, session_key, metadata=metadata
  3009. )
  3010. client = await self._get_chatto_client()
  3011. if client is None:
  3012. return SendResult(
  3013. success=False, error="Chatto client not available", retryable=True
  3014. )
  3015. number_emojis = _PROMPT_NUMBER_EMOJIS
  3016. emojis = [number_emojis[i] for i in range(len(choices))]
  3017. other_emoji = _PROMPT_OTHER_EMOJI
  3018. lines = [f"❓ {question}", ""]
  3019. for i, choice in enumerate(choices):
  3020. lines.append(f"{emojis[i]} {choice}")
  3021. lines.append(f"{other_emoji} Other (type your answer)")
  3022. content = "\n".join(lines)
  3023. # The card must carry the conversation's thread: an answer to it is
  3024. # routed by session key, and a card outside the thread keys to a
  3025. # different session than the one waiting for the answer.
  3026. thread_id = self._resolve_outbound_thread(chat_id, None, metadata)
  3027. try:
  3028. msg = await client.post_message(
  3029. room_id=str(chat_id),
  3030. body=content,
  3031. thread_root_event_id=str(thread_id) if thread_id else "",
  3032. )
  3033. except ChattoError as e:
  3034. logger.warning("Chatto: send_clarify post failed: %s", e)
  3035. return SendResult(success=False, error=str(e), retryable=True)
  3036. except Exception as e:
  3037. logger.warning("Chatto: send_clarify post error: %s", e)
  3038. return SendResult(success=False, error=str(e), retryable=False)
  3039. message_id = str(msg.id)
  3040. if message_id:
  3041. self._mark_seen(message_id)
  3042. for emoji in [*emojis, other_emoji]:
  3043. try:
  3044. await client.add_reaction(
  3045. room_id=str(chat_id),
  3046. message_event_id=message_id,
  3047. emoji=_shortcode_for_reaction_emoji(emoji),
  3048. )
  3049. except Exception:
  3050. logger.debug("Chatto: seed reaction %s failed", emoji, exc_info=True)
  3051. prompt = _ClarifyPrompt(
  3052. clarify_id=clarify_id,
  3053. choices=list(choices),
  3054. session_key=session_key,
  3055. chat_id=str(chat_id),
  3056. message_id=message_id,
  3057. expires_at=time.monotonic() + INTERACTIVE_PROMPT_TIMEOUT_SECONDS,
  3058. )
  3059. self._clarify_prompts[message_id] = prompt
  3060. self._clarify_id_to_message[clarify_id] = message_id
  3061. if thread_id:
  3062. try:
  3063. await client.follow_thread(chat_id, thread_id)
  3064. except Exception:
  3065. logger.debug(
  3066. "Chatto: clarify follow_thread failed for %s/%s",
  3067. chat_id,
  3068. thread_id,
  3069. exc_info=True,
  3070. )
  3071. return SendResult(success=True, message_id=message_id)
  3072. async def retire_clarify_card(self, clarify_id: str, notice: str) -> None:
  3073. """Rewrite a still-live clarify card into a terminal, button-less state.
  3074. The gateway calls this whenever it ends a clarify without a click — the
  3075. wait timed out, the session was reset, or unmatched free prose superseded
  3076. the prompt — so the card stops advertising an answer path the released
  3077. clarify can no longer accept. Keyed by ``clarify_id``, so a late call
  3078. cannot touch a newer prompt; no-op once resolved.
  3079. BasePlatformAdapter override
  3080. """
  3081. message_id = self._clarify_id_to_message.pop(clarify_id, None)
  3082. if message_id is None:
  3083. return
  3084. prompt = self._clarify_prompts.get(message_id)
  3085. if prompt is None:
  3086. return
  3087. prompt.resolved = True
  3088. terminal = f"❌ {notice}"
  3089. try:
  3090. await self.edit_message(prompt.chat_id, message_id, terminal)
  3091. except Exception:
  3092. logger.debug("Chatto: retire_clarify_card edit failed", exc_info=True)
  3093. self._clarify_prompts.pop(message_id, None)
  3094. async def _send_exec_approval_prompt(
  3095. self, prompt: ExecApprovalPrompt
  3096. ) -> SendResult:
  3097. """Post a reaction-driven exec-approval prompt.
  3098. BasePlatformAdapter override
  3099. """
  3100. choices = list(prompt.choices)
  3101. choices_map: dict[str, str] = {}
  3102. emojis: list[str] = []
  3103. for i, choice in enumerate(choices):
  3104. emoji = _PROMPT_APPROVAL_EMOJIS.get(choice)
  3105. if emoji is None:
  3106. emoji = (
  3107. _PROMPT_NUMBER_EMOJIS[i] if i < len(_PROMPT_NUMBER_EMOJIS) else "🔢"
  3108. )
  3109. emojis.append(emoji)
  3110. # Keys in the normalized form: reaction matching looks the
  3111. # incoming emoji up here after _normalize_reaction_emoji.
  3112. choices_map[_normalize_reaction_emoji(emoji)] = choice
  3113. client = await self._get_chatto_client()
  3114. if client is None:
  3115. return SendResult(
  3116. success=False, error="Chatto client not available", retryable=True
  3117. )
  3118. smart_denied = bool(prompt.smart_denied)
  3119. tier = "once"
  3120. if not smart_denied:
  3121. if "always" in choices:
  3122. tier = "always"
  3123. elif "session" in choices:
  3124. tier = "session"
  3125. typed_hints = {
  3126. "once": "React with ✅ to approve once.",
  3127. "session": "React with 🌀 to approve for this session.",
  3128. "always": "React with ♾️ to approve always.",
  3129. }
  3130. typed_hint = typed_hints.get(tier, "")
  3131. lines = [str(prompt.text), ""]
  3132. if typed_hint:
  3133. lines.append(typed_hint)
  3134. lines.append("")
  3135. lines.append("Legend:")
  3136. for emoji, choice in choices_map.items():
  3137. lines.append(f"{emoji} {choice}")
  3138. content = "\n".join(lines)
  3139. try:
  3140. # Same thread logic as send_clarify: the card must land in the
  3141. # conversation's thread, or a text answer to it keys to a session
  3142. # that is not the one waiting on the approval.
  3143. thread_id = self._resolve_outbound_thread(
  3144. str(prompt.chat_id), None, prompt.metadata
  3145. )
  3146. msg = await client.post_message(
  3147. room_id=str(prompt.chat_id),
  3148. body=content,
  3149. thread_root_event_id=str(thread_id) if thread_id else "",
  3150. )
  3151. except ChattoError as e:
  3152. logger.warning("Chatto: send_exec_approval post failed: %s", e)
  3153. return SendResult(success=False, error=str(e), retryable=True)
  3154. except Exception as e:
  3155. logger.warning("Chatto: send_exec_approval post error: %s", e)
  3156. return SendResult(success=False, error=str(e), retryable=False)
  3157. message_id = str(msg.id)
  3158. if message_id:
  3159. self._mark_seen(message_id)
  3160. for emoji in emojis:
  3161. try:
  3162. await client.add_reaction(
  3163. room_id=str(prompt.chat_id),
  3164. message_event_id=message_id,
  3165. emoji=_shortcode_for_reaction_emoji(emoji),
  3166. )
  3167. except Exception:
  3168. logger.debug("Chatto: seed reaction %s failed", emoji, exc_info=True)
  3169. approval_prompt = _ApprovalPrompt(
  3170. session_key=str(prompt.session_key),
  3171. chat_id=str(prompt.chat_id),
  3172. message_id=message_id,
  3173. choices_map=choices_map,
  3174. expires_at=time.monotonic() + INTERACTIVE_PROMPT_TIMEOUT_SECONDS,
  3175. )
  3176. self._approval_prompts[message_id] = approval_prompt
  3177. if thread_id:
  3178. try:
  3179. await client.follow_thread(str(prompt.chat_id), thread_id)
  3180. except Exception:
  3181. logger.debug(
  3182. "Chatto: approval follow_thread failed for %s/%s",
  3183. prompt.chat_id,
  3184. thread_id,
  3185. exc_info=True,
  3186. )
  3187. return SendResult(success=True, message_id=message_id)
  3188. async def edit_message(
  3189. self,
  3190. chat_id: str,
  3191. message_id: str,
  3192. content: str,
  3193. *,
  3194. finalize: bool = False,
  3195. ) -> SendResult:
  3196. """Edit a message we previously sent, via MessageService/UpdateMessage.
  3197. The stream consumer drives streaming replies through this: without the
  3198. override the base class reports "Not supported" and every incremental
  3199. update arrives as a *new* message.
  3200. ``finalize`` is a no-op for Chatto — an edit is an edit here, there is
  3201. no in-progress card state to close out (hence no
  3202. ``REQUIRES_EDIT_FINALIZE``).
  3203. Content that exceeds the per-message limit is refused rather than
  3204. silently truncated, so the caller falls back to ``send()``, which
  3205. splits across messages.
  3206. BasePlatformAdapter override
  3207. """
  3208. if not message_id:
  3209. return SendResult(success=False, error="Chatto: no message id to edit")
  3210. if not content:
  3211. return SendResult(success=False, error="Empty message")
  3212. formatted = self.format_message(content)
  3213. if len(formatted) > ChattoConstants.MAX_MESSAGE_LENGTH:
  3214. # Refuse instead of truncating: the caller's fallback path splits.
  3215. return SendResult(
  3216. success=False,
  3217. error=(
  3218. f"Chatto: edit exceeds {ChattoConstants.MAX_MESSAGE_LENGTH} "
  3219. f"chars ({len(formatted)})"
  3220. ),
  3221. )
  3222. client = await self._get_chatto_client()
  3223. if client is None:
  3224. return SendResult(
  3225. success=False, error="Chatto client not available", retryable=True
  3226. )
  3227. try:
  3228. msg = await client.update_message(
  3229. room_id=str(chat_id),
  3230. event_id=str(message_id),
  3231. body=formatted,
  3232. )
  3233. except ChattoError as e:
  3234. logger.warning("Chatto: UpdateMessage failed for %s: %s", message_id, e)
  3235. return SendResult(success=False, error=str(e), retryable=True)
  3236. except Exception as e:
  3237. logger.warning("Chatto: UpdateMessage error for %s: %s", message_id, e)
  3238. return SendResult(success=False, error=str(e), retryable=False)
  3239. # Our own edit comes back as a message_edited event; mark it seen so it
  3240. # is never mistaken for inbound traffic.
  3241. edited_id = msg.id or str(message_id)
  3242. self._mark_seen(edited_id)
  3243. return SendResult(success=True, message_id=edited_id)
  3244. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  3245. """Delete a message via MessageService/DeleteMessage.
  3246. Used by the stream consumer's fresh-final cleanup (removing a preview
  3247. message once the completed reply has been sent) and by the ephemeral
  3248. reply TTL.
  3249. BasePlatformAdapter override
  3250. """
  3251. if not chat_id or not message_id:
  3252. return False
  3253. client = await self._get_chatto_client()
  3254. if client is None:
  3255. logger.warning("Chatto: DeleteMessage — client unavailable")
  3256. return False
  3257. try:
  3258. return bool(
  3259. await client.delete_message(
  3260. room_id=str(chat_id),
  3261. event_id=str(message_id),
  3262. )
  3263. )
  3264. except ChattoError as e:
  3265. logger.warning("Chatto: DeleteMessage failed for %s: %s", message_id, e)
  3266. return False
  3267. except Exception as e:
  3268. logger.warning("Chatto: DeleteMessage error for %s: %s", message_id, e)
  3269. return False
  3270. async def create_handoff_thread(
  3271. self,
  3272. parent_chat_id: str,
  3273. name: str,
  3274. ) -> str | None:
  3275. """Anchor a session handoff in a fresh thread under *parent_chat_id*.
  3276. Chatto threads hang off a message, not off the room, so we post a seed
  3277. message and hand its ID back as the thread root — the same shape the
  3278. Slack adapter uses. DMs don't support threads, so they get ``None``
  3279. and the watcher keeps delivering into the DM itself.
  3280. BasePlatformAdapter override
  3281. """
  3282. if not parent_chat_id:
  3283. return None
  3284. if self._room_kinds.get(parent_chat_id) == RoomKind.DM:
  3285. logger.debug("Chatto: handoff thread skipped — %s is a DM", parent_chat_id)
  3286. return None
  3287. client = await self._get_chatto_client()
  3288. if client is None:
  3289. logger.warning("Chatto: handoff thread — client unavailable")
  3290. return None
  3291. try:
  3292. msg = await client.post_message(
  3293. room_id=str(parent_chat_id),
  3294. body=f"🧵 Hermes handoff — **{(name or 'session').strip()[:80]}**",
  3295. )
  3296. except Exception as e:
  3297. logger.warning(
  3298. "Chatto: handoff thread seed-post failed for room %s: %s",
  3299. parent_chat_id,
  3300. e,
  3301. )
  3302. return None
  3303. seed_id = msg.id
  3304. if not seed_id:
  3305. logger.warning("Chatto: handoff thread seed-post returned no message id")
  3306. return None
  3307. self._mark_seen(seed_id)
  3308. try:
  3309. await client.follow_thread(str(parent_chat_id), seed_id)
  3310. except Exception:
  3311. logger.debug(
  3312. "Chatto: follow_thread failed for handoff %s/%s",
  3313. parent_chat_id,
  3314. seed_id,
  3315. exc_info=True,
  3316. )
  3317. return seed_id
  3318. # Overridden from BaseAdapter:
  3319. async def send_typing(self, chat_id: str, metadata=None) -> None:
  3320. """Start a persistent typing indicator for a room.
  3321. Sends a typing ping every 10 seconds (Chatto's indicator likely
  3322. lasts ~8-10s). The background loop runs until ``stop_typing()``
  3323. is called or the task is cancelled.
  3324. BasePlatformAdapter override
  3325. """
  3326. if chat_id in self._typing_tasks:
  3327. return # already running
  3328. async def _typing_loop() -> None:
  3329. try:
  3330. while True:
  3331. try:
  3332. client = await self._get_chatto_client()
  3333. if client is None:
  3334. return
  3335. await client.refresh_typing_indicator(room_id=str(chat_id))
  3336. except asyncio.CancelledError:
  3337. return
  3338. except Exception:
  3339. logger.debug(
  3340. "Chatto: typing indicator refresh failed for %s",
  3341. chat_id,
  3342. exc_info=True,
  3343. )
  3344. await asyncio.sleep(10)
  3345. except asyncio.CancelledError:
  3346. pass
  3347. finally:
  3348. self._typing_tasks.pop(chat_id, None)
  3349. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  3350. async def stop_typing(self, chat_id: str) -> None:
  3351. """Stop the persistent typing indicator for a room.
  3352. BasePlatformAdapter override
  3353. """
  3354. task = self._typing_tasks.pop(chat_id, None)
  3355. if task:
  3356. task.cancel()
  3357. try:
  3358. await task
  3359. except (asyncio.CancelledError, Exception):
  3360. logger.debug("Chatto: typing task ended for %s", chat_id, exc_info=True)
  3361. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  3362. """Get information about a chat/room.
  3363. BasePlatformAdapter override
  3364. """
  3365. name = self._room_names.get(chat_id, chat_id)
  3366. kind = self._room_kinds.get(chat_id)
  3367. return {
  3368. "name": name,
  3369. "type": chat_type_for_room_kind(kind).value,
  3370. }
  3371. # ------------------------------------------------------------------ #
  3372. # Reactions
  3373. # ------------------------------------------------------------------ #
  3374. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  3375. """Add a reaction to a message via MessageService/AddReaction.
  3376. BasePlatformAdapter override
  3377. """
  3378. shortcode = _shortcode_for_reaction_emoji(emoji)
  3379. client = await self._get_chatto_client()
  3380. if client is None:
  3381. logger.warning("Chatto: AddReaction — client unavailable")
  3382. return False
  3383. try:
  3384. result = await client.add_reaction(
  3385. room_id=room_id,
  3386. message_event_id=message_id,
  3387. emoji=shortcode,
  3388. )
  3389. return result
  3390. except ChattoError as e:
  3391. logger.warning("Chatto: AddReaction failed: %s", e)
  3392. return False
  3393. except Exception as e:
  3394. logger.warning("Chatto: AddReaction error: %s", e)
  3395. return False
  3396. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  3397. """Remove a reaction from a message via MessageService/RemoveReaction.
  3398. BasePlatformAdapter override
  3399. """
  3400. shortcode = _shortcode_for_reaction_emoji(emoji)
  3401. client = await self._get_chatto_client()
  3402. if client is None:
  3403. logger.warning("Chatto: RemoveReaction — client unavailable")
  3404. return False
  3405. try:
  3406. result = await client.remove_reaction(
  3407. room_id=str(chat_id),
  3408. message_event_id=str(message_id),
  3409. emoji=shortcode,
  3410. )
  3411. return result
  3412. except ChattoError as e:
  3413. logger.warning("Chatto: RemoveReaction failed: %s", e)
  3414. return False
  3415. except Exception as e:
  3416. logger.warning("Chatto: RemoveReaction error: %s", e)
  3417. return False
  3418. # NOTE: there is deliberately no start_dm(). On Chatto only a person can
  3419. # start a DM ("Only people can start a DM... A bot cannot start a DM, even
  3420. # with message.post", dev-docs/guides/operations/permissions), and nothing
  3421. # in Hermes calls such a method — BasePlatformAdapter does not even declare
  3422. # one. An earlier version had it and advertised "DM initiation" in the
  3423. # capability banner, but it could only ever fail: the vendored chattolib's
  3424. # start_dm() calls a service stub that does not exist, so the AttributeError
  3425. # was swallowed into a silent None. DMs become usable the moment the other
  3426. # person writes to the bot; /join and the chatto_send_dm tool both say so.
  3427. # ------------------------------------------------------------------ #
  3428. # Room creation (Chatto-unique)
  3429. # ------------------------------------------------------------------ #
  3430. async def create_room(
  3431. self,
  3432. name: str,
  3433. description: str = "",
  3434. group_id: str = "",
  3435. universal: bool = True,
  3436. ) -> str | None:
  3437. """Create an ad-hoc room via RoomService/CreateRoom.
  3438. Returns the room ID on success, or None on failure.
  3439. BasePlatformAdapter override
  3440. """
  3441. client = await self._get_chatto_client()
  3442. if client is None:
  3443. return None
  3444. try:
  3445. room = await client.create_room(
  3446. name=name,
  3447. group_id=group_id or "",
  3448. description=description,
  3449. universal=universal,
  3450. )
  3451. rid = str(room.id) if room else ""
  3452. if rid:
  3453. self._room_names[rid] = room.name
  3454. self._room_kinds[rid] = room.kind
  3455. return rid
  3456. logger.debug("Chatto: CreateRoom returned no room id")
  3457. return None
  3458. except ChattoError as e:
  3459. logger.debug("Chatto: CreateRoom failed: %s", e)
  3460. return None
  3461. except Exception as e:
  3462. logger.debug("Chatto: CreateRoom error: %s", e)
  3463. return None
  3464. # ------------------------------------------------------------------ #
  3465. # Processing lifecycle hooks (reactions-based, like Discord)
  3466. # ------------------------------------------------------------------ #
  3467. def _event_room_and_message_id(self, event: MessageEvent) -> tuple[str, str]:
  3468. """Extract room_id and message_id from a MessageEvent."""
  3469. message_id = event.message_id or ""
  3470. return event.source.chat_id, message_id
  3471. async def on_processing_start(self, event: MessageEvent) -> None:
  3472. """Record the turn as open, then add an 👀 (eyes) reaction.
  3473. The record is what lets an edit of this very message be recognized as
  3474. a mid-run correction. It must be maintained even when reactions are
  3475. disabled — tracking and decorating are independent concerns.
  3476. BasePlatformAdapter override
  3477. """
  3478. session_key = (
  3479. self._session_key_for(event.source) if event.source is not None else ""
  3480. )
  3481. if session_key and event.message_id:
  3482. self._processing[session_key] = str(event.message_id)
  3483. if not self.chatto_config.reactions.value:
  3484. return
  3485. chat_id, message_id = self._event_room_and_message_id(event)
  3486. if not chat_id or not message_id:
  3487. # Routine, not a fault: the gateway runs agent-initiated turns
  3488. # (heartbeat polls, goal continuations) through the same pipeline
  3489. # with message_id=None, and there is no inbound message to mark.
  3490. logger.debug(
  3491. "Chatto: nothing to react to (chat_id=%r, message_id=%r)",
  3492. chat_id,
  3493. message_id,
  3494. )
  3495. return
  3496. await self.add_reaction(chat_id, message_id, "👀")
  3497. async def on_processing_complete(
  3498. self,
  3499. event: MessageEvent,
  3500. outcome: ProcessingOutcome,
  3501. ) -> None:
  3502. """Close the turn's record, then swap 👀 for ✅/❌/🚫.
  3503. Fires for every outcome, including CANCELLED (mid-run edit
  3504. correction) — this is what re-arms `_processing` before the corrected
  3505. turn is dispatched.
  3506. BasePlatformAdapter override
  3507. """
  3508. session_key = (
  3509. self._session_key_for(event.source) if event.source is not None else ""
  3510. )
  3511. if session_key and event.message_id:
  3512. self._processing.pop(session_key, None)
  3513. if not self.chatto_config.reactions.value:
  3514. return
  3515. chat_id, message_id = self._event_room_and_message_id(event)
  3516. if not chat_id or not message_id:
  3517. return
  3518. # Remove the processing eyes reaction
  3519. await self.remove_reaction(chat_id, message_id, "👀")
  3520. # Add the outcome reaction
  3521. if outcome == ProcessingOutcome.SUCCESS:
  3522. await self.add_reaction(chat_id, message_id, "✅")
  3523. elif outcome == ProcessingOutcome.FAILURE:
  3524. await self.add_reaction(chat_id, message_id, "❌")
  3525. elif outcome == ProcessingOutcome.CANCELLED:
  3526. await self.add_reaction(chat_id, message_id, "🚫")
  3527. # ------------------------------------------------------------------ #
  3528. # Asset upload (chunked)
  3529. # ------------------------------------------------------------------ #
  3530. async def _upload_asset(self, room_id: str, file_path: str) -> str | None:
  3531. """Upload a file via the chunked AssetUploadService.
  3532. Returns the asset ID on success, or None on failure.
  3533. """
  3534. try:
  3535. file_data = await asyncio.to_thread(_read_file_bytes, file_path)
  3536. except Exception as e:
  3537. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  3538. return None
  3539. if not file_data:
  3540. logger.error("Chatto: file %s is empty", file_path)
  3541. return None
  3542. file_size = len(file_data)
  3543. file_name = os.path.basename(file_path)
  3544. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  3545. sha256_hash = hashlib.sha256(file_data).hexdigest()
  3546. client = await self._get_chatto_client()
  3547. if client is None:
  3548. logger.error("Chatto: upload aborted - no client available")
  3549. return None
  3550. try:
  3551. # Step 1: Create upload session
  3552. upload = await client.create_upload(
  3553. room_id=room_id,
  3554. filename=file_name,
  3555. size=file_size,
  3556. sha256=sha256_hash,
  3557. content_type=mime_type,
  3558. )
  3559. # AssetUpload names this upload_id, not id — reading it through an
  3560. # untyped getattr default is what let the mismatch reach production.
  3561. upload_id = upload.upload_id
  3562. if not upload_id:
  3563. logger.error("Chatto: CreateUpload returned no upload ID")
  3564. return None
  3565. # Step 2: Upload chunks
  3566. offset = 0
  3567. while offset < file_size:
  3568. chunk = file_data[offset : offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  3569. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  3570. await client.upload_chunk(
  3571. upload_id=upload_id,
  3572. offset=offset,
  3573. content=chunk,
  3574. chunk_sha256=chunk_sha256,
  3575. )
  3576. offset += len(chunk)
  3577. # Step 3: Complete upload
  3578. upload, asset = await client.complete_upload(upload_id=upload_id)
  3579. if not asset:
  3580. logger.error("Chatto: CompleteUpload returned no asset")
  3581. return None
  3582. logger.info(
  3583. "Chatto: uploaded %s as asset %s (%d bytes)",
  3584. file_name,
  3585. asset.id,
  3586. file_size,
  3587. )
  3588. return asset.id
  3589. except ChattoError as e:
  3590. logger.error("Chatto: upload failed: %s", e)
  3591. return None
  3592. except Exception as e:
  3593. logger.error("Chatto: upload error: %s", e)
  3594. return None
  3595. async def _post_attachment_message(
  3596. self,
  3597. chat_id: str,
  3598. asset_ids: list[str],
  3599. caption: str | None,
  3600. reply_to: str | None,
  3601. metadata: dict[str, Any] | None,
  3602. ) -> SendResult:
  3603. """Post one message carrying already-uploaded assets.
  3604. Threading follows the same rules as a text send
  3605. (:meth:`_resolve_outbound_thread`), so with ``auto_thread`` disabled an
  3606. attachment reply lands in the room like its text counterpart instead of
  3607. quietly opening a thread.
  3608. """
  3609. thread_id = self._resolve_outbound_thread(chat_id, reply_to, metadata)
  3610. client = await self._get_chatto_client()
  3611. if client is None:
  3612. return SendResult(
  3613. success=False, error="Chatto client not available", retryable=True
  3614. )
  3615. try:
  3616. msg = await client.post_message(
  3617. room_id=str(chat_id),
  3618. body=self.format_message(caption) if caption else "",
  3619. attachment_asset_ids=asset_ids,
  3620. thread_root_event_id=thread_id or "",
  3621. )
  3622. self._mark_seen(msg.id)
  3623. return SendResult(success=True, message_id=msg.id)
  3624. except ChattoError as e:
  3625. # Same classification as the chunked text path: server-side
  3626. # failures retry, anything else is ours and must not loop.
  3627. return SendResult(success=False, error=str(e), retryable=True)
  3628. except Exception as e:
  3629. return SendResult(success=False, error=str(e), retryable=False)
  3630. async def _send_local_file_as_attachment(
  3631. self,
  3632. chat_id: str,
  3633. file_path: str,
  3634. caption: str | None,
  3635. reply_to: str | None,
  3636. metadata: dict[str, Any] | None,
  3637. *,
  3638. kind: str,
  3639. ) -> SendResult:
  3640. """Upload a local file and post it as a native Chatto attachment.
  3641. Shared by ``send_image_file``/``send_document``/``send_video``/
  3642. ``send_voice`` — the upload mechanics are identical, only the wording of
  3643. the failure notice differs. On failure we send that notice as text and
  3644. never the host path (it leaks the Hermes home layout).
  3645. """
  3646. notice = f"⚠️ Couldn't deliver the {kind} attachment."
  3647. safe_path = self.validate_media_delivery_path(file_path)
  3648. if not safe_path:
  3649. logger.warning(
  3650. "[%s] send %s: unsafe path %s",
  3651. self.name,
  3652. kind,
  3653. file_path,
  3654. )
  3655. text = f"{caption}\n{notice}" if caption else notice
  3656. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  3657. asset_id = await self._upload_asset(str(chat_id), safe_path)
  3658. if not asset_id:
  3659. logger.warning(
  3660. "[%s] send %s: upload failed for %s",
  3661. self.name,
  3662. kind,
  3663. safe_path,
  3664. )
  3665. text = f"{caption}\n{notice}" if caption else notice
  3666. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  3667. return await self._post_attachment_message(
  3668. chat_id,
  3669. [asset_id],
  3670. caption,
  3671. reply_to,
  3672. metadata,
  3673. )
  3674. async def send_image_file(
  3675. self,
  3676. chat_id: str,
  3677. image_path: str,
  3678. caption: str | None = None,
  3679. reply_to: str | None = None,
  3680. metadata: dict[str, Any] | None = None,
  3681. **kwargs,
  3682. ) -> SendResult:
  3683. """Send a local image file via the chunked upload API.
  3684. The parameter is ``image_path``, not ``file_path``: every caller passes
  3685. it by keyword (``gateway/run.py:22354``, ``:22470``, and the base class's
  3686. own ``send_multiple_images`` file:// branch), so a renamed parameter
  3687. makes each of those raise TypeError and silently degrade to a text
  3688. notice.
  3689. BasePlatformAdapter override
  3690. """
  3691. return await self._send_local_file_as_attachment(
  3692. chat_id,
  3693. image_path,
  3694. caption,
  3695. reply_to,
  3696. metadata,
  3697. kind="image",
  3698. )
  3699. async def send_document(
  3700. self,
  3701. chat_id: str,
  3702. file_path: str,
  3703. caption: str | None = None,
  3704. file_name: str | None = None,
  3705. reply_to: str | None = None,
  3706. metadata: dict[str, Any] | None = None,
  3707. **kwargs,
  3708. ) -> SendResult:
  3709. """Send a local file as a native Chatto attachment.
  3710. ``file_name`` exists in the base-class signature and is accepted for
  3711. compatibility, but Chatto takes the recipient-visible filename from
  3712. the upload session (derived from the local path); failures are logged
  3713. and noticed by ``_send_local_file_as_attachment`` itself.
  3714. BasePlatformAdapter override
  3715. """
  3716. return await self._send_local_file_as_attachment(
  3717. chat_id,
  3718. file_path,
  3719. caption,
  3720. reply_to,
  3721. metadata,
  3722. kind="file",
  3723. )
  3724. async def send_video(
  3725. self,
  3726. chat_id: str,
  3727. video_path: str,
  3728. caption: str | None = None,
  3729. reply_to: str | None = None,
  3730. metadata: dict[str, Any] | None = None,
  3731. **kwargs,
  3732. ) -> SendResult:
  3733. """Send a local video as a native Chatto attachment.
  3734. Chatto transcodes and plays it inline.
  3735. BasePlatformAdapter override
  3736. """
  3737. return await self._send_local_file_as_attachment(
  3738. chat_id,
  3739. video_path,
  3740. caption,
  3741. reply_to,
  3742. metadata,
  3743. kind="video",
  3744. )
  3745. async def send_voice(
  3746. self,
  3747. chat_id: str,
  3748. audio_path: str,
  3749. caption: str | None = None,
  3750. reply_to: str | None = None,
  3751. metadata: dict[str, Any] | None = None,
  3752. **kwargs,
  3753. ) -> SendResult:
  3754. """Send a local audio file as a native Chatto attachment.
  3755. Chatto has no dedicated voice-bubble type, so this is an ordinary audio
  3756. attachment — still far better than the base class's text notice.
  3757. BasePlatformAdapter override
  3758. """
  3759. return await self._send_local_file_as_attachment(
  3760. chat_id,
  3761. audio_path,
  3762. caption,
  3763. reply_to,
  3764. metadata,
  3765. kind="audio",
  3766. )
  3767. async def send_image(
  3768. self,
  3769. chat_id: str,
  3770. image_url: str,
  3771. caption: str | None = None,
  3772. reply_to: str | None = None,
  3773. metadata: dict[str, Any] | None = None,
  3774. ) -> SendResult:
  3775. """Send an image to a Chatto room.
  3776. Materialises the URL (size-capped download, like every inbound
  3777. attachment) and uploads it as a native attachment. Falls back to the
  3778. plain URL as a link — Chatto renders link previews — when the URL
  3779. cannot be materialised or the post after a successful upload fails.
  3780. An upload failure needs no fallback on top: the text notice of
  3781. ``_send_local_file_as_attachment`` has already gone out.
  3782. BasePlatformAdapter override
  3783. """
  3784. link_text = f"{caption}\n{image_url}" if caption else image_url
  3785. path, is_temp = await self._materialise_image(image_url)
  3786. if path is not None:
  3787. try:
  3788. result = await self._send_local_file_as_attachment(
  3789. chat_id, path, caption, reply_to, metadata, kind="image"
  3790. )
  3791. finally:
  3792. if is_temp:
  3793. try:
  3794. os.unlink(path)
  3795. except OSError:
  3796. pass
  3797. if result.success:
  3798. return result
  3799. return await self.send(chat_id, link_text, reply_to=reply_to, metadata=metadata)
  3800. async def _materialise_image(self, image_url: str) -> tuple[str | None, bool]:
  3801. """Resolve one ``send_multiple_images`` entry to a local file path.
  3802. Accepts ``http(s)://`` URLs (downloaded to a temp file), ``file://``
  3803. URIs and bare paths. Returns ``(path, is_temp)`` — the caller unlinks
  3804. when ``is_temp``. ``(None, False)`` means the entry is unusable.
  3805. """
  3806. if image_url.startswith(("http://", "https://")):
  3807. ext = os.path.splitext(urlsplit(image_url).path)[1] or ".png"
  3808. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  3809. os.close(tmp_fd)
  3810. try:
  3811. data = await self._download_attachment_bytes(image_url)
  3812. await asyncio.to_thread(_write_file_bytes, tmp_path, data)
  3813. except Exception as e:
  3814. logger.warning("Chatto: image download failed for %s: %s", image_url, e)
  3815. try:
  3816. os.unlink(tmp_path)
  3817. except OSError:
  3818. pass
  3819. return None, False
  3820. return tmp_path, True
  3821. local = image_url
  3822. if local.startswith("file://"):
  3823. local = unquote(urlsplit(local).path)
  3824. return self.validate_media_delivery_path(local), False
  3825. async def send_multiple_images(
  3826. self,
  3827. chat_id: str,
  3828. images: list[tuple[str, str]],
  3829. metadata: dict[str, Any] | None = None,
  3830. human_delay: float = 0.0,
  3831. ) -> SendResult:
  3832. """Send a batch of images as ONE message with several attachments.
  3833. The base implementation posts each image separately; a Chatto message
  3834. carries a list of attachment assets, so a batch belongs in a single
  3835. message (and a single notification).
  3836. ``human_delay`` is ignored deliberately — there is only one outbound
  3837. call to pace. Entries that can't be fetched are dropped with a warning;
  3838. if nothing survives, we fall back to the base class so the user still
  3839. gets the links.
  3840. BasePlatformAdapter override
  3841. """
  3842. if len(images or []) < 2:
  3843. return await super().send_multiple_images(
  3844. chat_id,
  3845. images,
  3846. metadata=metadata,
  3847. human_delay=human_delay,
  3848. )
  3849. asset_ids: list[str] = []
  3850. captions: list[str] = []
  3851. for image_url, alt_text in images:
  3852. path, is_temp = await self._materialise_image(image_url)
  3853. if not path:
  3854. logger.warning("Chatto: skipping unusable image %s", image_url)
  3855. continue
  3856. try:
  3857. asset_id = await self._upload_asset(str(chat_id), path)
  3858. finally:
  3859. if is_temp:
  3860. try:
  3861. os.unlink(path)
  3862. except OSError:
  3863. pass
  3864. if not asset_id:
  3865. logger.warning("Chatto: upload failed for image %s", image_url)
  3866. continue
  3867. asset_ids.append(asset_id)
  3868. if alt_text:
  3869. captions.append(alt_text)
  3870. if not asset_ids:
  3871. logger.warning(
  3872. "Chatto: no image survived upload, falling back to per-image delivery",
  3873. )
  3874. return await super().send_multiple_images(
  3875. chat_id,
  3876. images,
  3877. metadata=metadata,
  3878. human_delay=human_delay,
  3879. )
  3880. if len(asset_ids) < len(images):
  3881. logger.warning(
  3882. "Chatto: sending %d of %d images — the rest could not be uploaded",
  3883. len(asset_ids),
  3884. len(images),
  3885. )
  3886. return await self._post_attachment_message(
  3887. chat_id,
  3888. asset_ids,
  3889. "\n".join(captions) or None,
  3890. None,
  3891. metadata,
  3892. )
  3893. # ---------------------------------------------------------------------------
  3894. # Cron / out-of-process delivery
  3895. # ---------------------------------------------------------------------------
  3896. async def hermes_standalone_sender_fn(
  3897. pconfig: PlatformConfig,
  3898. chat_id: str,
  3899. message: str,
  3900. *,
  3901. thread_id=None,
  3902. media_files=None,
  3903. force_document=False,
  3904. ) -> SendResult:
  3905. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  3906. Used by cron / scheduled routines that run out-of-process. Creates a
  3907. short-lived chattolib client, posts, and closes. Long messages are
  3908. normalised and split like ``send()`` does, so cron output cannot die on
  3909. the server's per-message limit.
  3910. """
  3911. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  3912. # Create a temporary client for standalone sending — needs a base URL and token.
  3913. has_token = bool(chatto_config.token.value)
  3914. if not chatto_config.base_url.value or not has_token:
  3915. return SendResult(success=False, error="Chatto: base URL or token missing")
  3916. client = ChattoClient(
  3917. base_url=chatto_config.base_url.value, token=chatto_config.token.value
  3918. )
  3919. try:
  3920. kwargs: dict[str, Any] = {}
  3921. if chatto_config.auto_thread.value and thread_id:
  3922. kwargs["thread_root_event_id"] = thread_id
  3923. if media_files and media_files.get("attachment_asset_ids"):
  3924. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  3925. formatted = _normalise_outbound_text(message)
  3926. chunks = BasePlatformAdapter.truncate_message(
  3927. formatted, ChattoConstants.SPLIT_THRESHOLD
  3928. )
  3929. message_ids: list[str] = []
  3930. try:
  3931. for chunk in chunks:
  3932. posted = await client.post_message(chat_id, chunk, **kwargs)
  3933. message_ids.append(posted.id)
  3934. except Exception as exc:
  3935. if message_ids:
  3936. logger.warning(
  3937. "Chatto standalone: sent %d/%d chunk(s) to %s before failing: %s",
  3938. len(message_ids),
  3939. len(chunks),
  3940. chat_id,
  3941. exc,
  3942. )
  3943. # Same classification as the adapter's send paths: only
  3944. # server-side failures read as retryable.
  3945. return SendResult(
  3946. success=False,
  3947. error=str(exc),
  3948. retryable=isinstance(exc, ChattoError),
  3949. )
  3950. return SendResult(success=True, message_id=message_ids[0])
  3951. finally:
  3952. try:
  3953. await client.close()
  3954. except Exception as exc:
  3955. logger.warning(
  3956. "Chatto standalone: error closing short-lived client (perhaps already closed): %s",
  3957. exc,
  3958. )
  3959. # Resolved Chatto configuration — populated by ``hermes_validate_config`` so
  3960. # plugin tools can access it without re-reading env vars or duplicating
  3961. # ``ChattoConfiguration`` logic.
  3962. #
  3963. # Keyed by the profile the snapshot was validated for, not stored in one slot:
  3964. # Hermes multiplexes several profiles through a single gateway process and runs
  3965. # every profile's own validate_config (run_adapters.py, one _create_adapter per
  3966. # profile), so a single global would be whichever profile validated last — and a
  3967. # routed cron fire or turn for another profile would then send with the wrong
  3968. # profile's bot token. The key is the same home key the platform registry scopes
  3969. # its own entries by, so both agree on what "the serving profile" means.
  3970. _resolved_chatto_configs: dict[str, ChattoConfiguration] = {}
  3971. def _profile_scope_key() -> str:
  3972. """Registry key of the profile being served right now.
  3973. Falls back to a constant when ``hermes_constants`` is unavailable (a bare
  3974. standalone sender process): one profile there, so one key loses nothing.
  3975. """
  3976. try:
  3977. from hermes_constants import hermes_home_key
  3978. return hermes_home_key()
  3979. except Exception:
  3980. logger.debug("Chatto: no profile scope key available", exc_info=True)
  3981. return ""
  3982. def _realtime_cursor_file() -> Path | None:
  3983. """Where a restart-resumable realtime cursor lives, or None without Hermes.
  3984. Under the profile's own home so two profiles never read each other's
  3985. position; ``None`` (a bare process with no ``hermes_constants``) simply
  3986. means nothing is persisted, which is the same behaviour as no config.
  3987. """
  3988. try:
  3989. from hermes_constants import get_hermes_home
  3990. except ImportError:
  3991. return None
  3992. return Path(get_hermes_home()) / "state" / "chatto_realtime_cursor.json"
  3993. def _restore_realtime_cursor(cfg: ChattoConfiguration) -> str | None:
  3994. """The stored realtime cursor, if it is this profile's and still fresh.
  3995. Three ways a stored value is refused instead of trusted: a different
  3996. profile wrote it, it carries a shape this build does not understand, or it
  3997. is older than ``resume_window``. In every case the stream starts at the
  3998. live boundary, which is what the plugin did before the cursor was stored at
  3999. all — so a bad file costs the gap it was meant to close, never a crash.
  4000. """
  4001. window = cfg.resume_window.value
  4002. if window <= 0:
  4003. return None
  4004. path = _realtime_cursor_file()
  4005. if path is None:
  4006. return None
  4007. try:
  4008. payload = json.loads(path.read_text(encoding="utf-8"))
  4009. except (OSError, ValueError):
  4010. return None
  4011. if not isinstance(payload, dict):
  4012. return None
  4013. if payload.get("scope") != _profile_scope_key():
  4014. return None
  4015. cursor = payload.get("cursor")
  4016. saved_at = payload.get("saved_at")
  4017. if not isinstance(cursor, str) or not cursor or not isinstance(saved_at, str):
  4018. return None
  4019. try:
  4020. saved = datetime.fromisoformat(saved_at)
  4021. except ValueError:
  4022. return None
  4023. if saved.tzinfo is None:
  4024. saved = saved.replace(tzinfo=UTC)
  4025. if (datetime.now(UTC) - saved).total_seconds() > window:
  4026. return None
  4027. return cursor
  4028. def _persist_realtime_cursor(cfg: ChattoConfiguration, cursor: str | None) -> None:
  4029. """Store the cursor of the last applied event, best-effort.
  4030. Written only on a clean stop, not per event: a deploy or restart should not
  4031. lose the gap, while a crash is allowed to — the alternative is a file write
  4032. on every presence change. A failed write is logged and otherwise ignored,
  4033. because losing the resume point is not a reason to fail a shutdown.
  4034. """
  4035. if not cursor or cfg.resume_window.value <= 0:
  4036. return
  4037. path = _realtime_cursor_file()
  4038. if path is None:
  4039. return
  4040. payload = {
  4041. "scope": _profile_scope_key(),
  4042. "cursor": cursor,
  4043. "saved_at": datetime.now(UTC).isoformat(),
  4044. }
  4045. try:
  4046. path.parent.mkdir(parents=True, exist_ok=True)
  4047. path.write_text(json.dumps(payload), encoding="utf-8")
  4048. except OSError as exc:
  4049. logger.debug("Chatto: realtime cursor not persisted: %s", exc)
  4050. # How similar an ``extra`` key must be to a declared config_key before the
  4051. # unknown-key check reads it as a likely typo or renamed field.
  4052. _NEAR_MISS_RATIO = 0.75
  4053. def _warn_on_unknown_extra_keys(config: PlatformConfig) -> None:
  4054. """Warn about ``extra`` keys that look like misspelled config fields.
  4055. A typo'd key silently resolves to the default otherwise — the warning is
  4056. the only thing telling the user their ``require_mention_channles`` never
  4057. reached us. Only near-matches against our declared config_keys are
  4058. flagged (difflib similarity): keys that resemble nothing of ours are
  4059. either placed there by the Hermes gateway itself (the shared-key loop in
  4060. load_gateway_config() bridges reply_in_thread & co. into every platform's
  4061. extra, hardcoded inline upstream — nothing to import) or are deliberate
  4062. pass-throughs, and flagging those would just train users to ignore us.
  4063. Internal markers (``_enabled_explicit``) are skipped outright.
  4064. """
  4065. extra: dict[str, Any] = getattr(config, "extra", None) or {}
  4066. known = [field.config_key for field in ChattoConfiguration.fields()]
  4067. for key in sorted(extra):
  4068. if key.startswith("_") or key in known:
  4069. continue
  4070. best = max(known, key=lambda k: SequenceMatcher(None, key, k).ratio())
  4071. if SequenceMatcher(None, key, best).ratio() >= _NEAR_MISS_RATIO:
  4072. logger.warning(
  4073. "Chatto: 'extra' key '%s' matches no config field — did you mean '%s'?",
  4074. key,
  4075. best,
  4076. )
  4077. def hermes_validate_config(config: PlatformConfig) -> bool:
  4078. """Check whether Chatto Plugin is configured.
  4079. Function name should be the same as register argument name with "hermes_" prefix, so we
  4080. know that it is needed for plugin register(). Do not change signature.
  4081. Takes ``config``. Compare to hermes_is_connected().
  4082. """
  4083. resolved = ChattoConfiguration(pconfig=config)
  4084. _warn_on_unknown_extra_keys(config)
  4085. if len(resolved.allowed_users.value) > 0 and resolved.allow_all_users.value:
  4086. logger.error(
  4087. "Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both."
  4088. )
  4089. return False
  4090. require_rooms = set(resolved.require_mention_rooms.value)
  4091. optional_rooms = set(resolved.optional_mention_rooms.value)
  4092. overlap = sorted(require_rooms & optional_rooms)
  4093. if overlap:
  4094. logger.error(
  4095. "Chatto: Conflicting configuration. Room(s) %s are on both "
  4096. "'require_mention_rooms' and 'optional_mention_rooms' — "
  4097. "each room must appear in at most one of them.",
  4098. ", ".join(overlap),
  4099. )
  4100. return False
  4101. if resolved.resume_window.value < 0:
  4102. logger.error(
  4103. "Chatto: 'resume_window' must be 0 (disabled) or a positive number "
  4104. "of seconds, not %s.",
  4105. resolved.resume_window.value,
  4106. )
  4107. return False
  4108. _by_room, malformed_toolsets = _parse_room_toolsets(resolved.room_toolsets.value)
  4109. if malformed_toolsets:
  4110. logger.error(
  4111. "Chatto: 'room_toolsets' entries must look like 'room_id:toolset' — "
  4112. "these could not be read: %s",
  4113. ", ".join(repr(entry) for entry in malformed_toolsets),
  4114. )
  4115. return False
  4116. # base_url always resolves (it defaults to ChattoHQ), so the only real
  4117. # question is whether a token came in.
  4118. if resolved.token.value is None:
  4119. logger.error("Chatto: CHATTO_TOKEN must be set.")
  4120. return False
  4121. # Publish for the plugin tools only now: a config we just rejected is not
  4122. # one they should send with, and a rejected call must not overwrite a
  4123. # snapshot an earlier, accepted call left behind.
  4124. _resolved_chatto_configs[_profile_scope_key()] = resolved
  4125. return True
  4126. def hermes_check_fn() -> bool:
  4127. """Report whether the vendored chattolib dependency can be imported."""
  4128. try:
  4129. from chattolib import (
  4130. client, # noqa: F401 — vendored dependency probe
  4131. )
  4132. return True
  4133. except ImportError:
  4134. return False
  4135. # ---------------------------------------------------------------------------
  4136. # is_connected probe
  4137. # ---------------------------------------------------------------------------
  4138. def hermes_is_connected(config: PlatformConfig) -> bool:
  4139. """Report whether the Chatto platform is configured and enabled.
  4140. The name is fixed by the register() contract, but despite what it
  4141. suggests this does not open a connection — it validates configuration
  4142. only (see :func:`hermes_validate_config`); the gateway probes real
  4143. connectivity through ``connect()``.
  4144. """
  4145. return bool(hermes_validate_config(config) and config.enabled)
  4146. def hermes_setup_fn() -> None:
  4147. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  4148. Function name should be the same as register argument name with "hermes_" prefix, so we
  4149. know that it is needed for plugin register().
  4150. """
  4151. from hermes_cli.setup import (
  4152. print_success,
  4153. prompt,
  4154. prompt_yes_no,
  4155. save_env_value,
  4156. )
  4157. url = prompt(
  4158. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:"
  4159. )
  4160. if url:
  4161. save_env_value(ChattoConfiguration.base_url.env_name, url)
  4162. token = prompt("Chatto bot token (cht_BK_...):", password=True)
  4163. if token:
  4164. save_env_value(ChattoConfiguration.token.env_name, token)
  4165. home = prompt("Home room ID for notifications (or empty):")
  4166. if home:
  4167. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  4168. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  4169. if allow_all:
  4170. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  4171. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  4172. def hermes_env_enablement_fn() -> dict:
  4173. """Seed PlatformConfig.extra from the CHATTO_* environment variables.
  4174. Returns a dict compatible with the PlatformConfig merge hook, holding
  4175. exactly the values that are actually set via env — never fabricated
  4176. defaults. Called by the platform registry during load_gateway_config(),
  4177. which commits this dict onto the platform's ``extra`` verbatim; seeding a
  4178. value that was not configured would overwrite what the user set in
  4179. config.yaml (e.g. a YAML base_url clobbered by the ChattoHQ default).
  4180. "Nothing set" therefore stays the adapter's business: every ConfigField
  4181. falls back to its declared default (base_url to ChattoHQ) on its own.
  4182. Seed keys are the config.yaml "extra" keys (config_key), NOT the env var
  4183. names — ChattoConfiguration reads extra[config_key]. The special
  4184. 'home_channel' key is extracted by the gateway and becomes a proper
  4185. HomeChannel dataclass on the PlatformConfig; every other key is merged
  4186. into PlatformConfig.extra.
  4187. Function name should be the same as register argument name with "hermes_" prefix, so we
  4188. know that it is needed for plugin register().
  4189. """
  4190. seed: dict[str, Any] = {}
  4191. for config_field in ChattoConfiguration.fields():
  4192. env_value = os.getenv(config_field.env_name)
  4193. if env_value:
  4194. seed[config_field.config_key] = env_value.strip()
  4195. logger.debug("seed: %s", {k: v for k, v in seed.items() if k != "token"})
  4196. return seed
  4197. # ---------------------------------------------------------------------------
  4198. # Plugin registration entry point
  4199. # ---------------------------------------------------------------------------
  4200. # What each capability is called in the startup banner, keyed by the method
  4201. # that implements it. Derived from real overrides rather than hard-coded, so
  4202. # dropping a method drops its claim from the log instead of leaving a lie.
  4203. _CAPABILITY_LABELS = {
  4204. "send": "text",
  4205. "send_image_file": "images",
  4206. "send_multiple_images": "image batches (bundled into one message)",
  4207. "send_video": "video",
  4208. "send_voice": "voice messages",
  4209. "send_document": "documents",
  4210. "add_reaction": "reactions",
  4211. "edit_message": "message editing",
  4212. "delete_message": "message deletion",
  4213. "send_typing": "typing indicators",
  4214. "create_handoff_thread": "threads",
  4215. "create_room": "room creation",
  4216. "toolsets_for_source": "per-room toolsets (CHATTO_ROOM_TOOLSETS)",
  4217. }
  4218. def _capabilities() -> list[str]:
  4219. """Name the things this adapter genuinely implements itself.
  4220. A capability counts only when ChattoAdapter overrides the base method —
  4221. inheriting BasePlatformAdapter's fallback means the feature is not
  4222. natively supported, and announcing it would mislead.
  4223. """
  4224. found = [
  4225. label
  4226. for name, label in _CAPABILITY_LABELS.items()
  4227. if getattr(ChattoAdapter, name, None)
  4228. is not getattr(BasePlatformAdapter, name, None)
  4229. ]
  4230. if ChattoAdapter.supports_code_blocks:
  4231. found.append("code blocks")
  4232. if ChattoAdapter.supports_status_text:
  4233. found.append("custom status text")
  4234. found.append("presence (refreshed while connected)")
  4235. return found
  4236. # --------------------------------------------------------------------------- #
  4237. # Plugin tools: send DM to a user, or send to a room
  4238. # --------------------------------------------------------------------------- #
  4239. class _ToolRefusal(Exception):
  4240. """A tool step that ends the call with a result for the model.
  4241. The rendered JSON travels on the exception, so every early exit reads the
  4242. same to Hermes and none of them escapes as an unhandled error.
  4243. """
  4244. def __init__(self, result_json: str) -> None:
  4245. super().__init__(result_json)
  4246. self.result_json = result_json
  4247. def _refuse(error: str, **extra: Any) -> _ToolRefusal:
  4248. """Build a refusal result, so every early exit agrees on the shape."""
  4249. return _ToolRefusal(json.dumps({"success": False, "error": error, **extra}))
  4250. def _int_arg(args: dict, key: str, default: int, *, low: int, high: int) -> int:
  4251. """An integer tool argument, validated — a refusal rather than a guess.
  4252. The value comes from a model, so "twenty" and a float are both reachable,
  4253. and an unvalidated ``int()`` would raise out of the handler instead of
  4254. answering. An absent argument takes the default; a *wrong* one is refused,
  4255. which also keeps a falsy ``0`` from silently becoming the default and
  4256. quietly widening the answer.
  4257. """
  4258. raw = args.get(key)
  4259. if raw is None or raw == "":
  4260. return default
  4261. not_a_number = f"{key} must be a whole number between {low} and {high}"
  4262. try:
  4263. value = int(raw)
  4264. except (TypeError, ValueError) as exc:
  4265. raise _refuse(not_a_number) from exc
  4266. if isinstance(raw, float) and not raw.is_integer():
  4267. # int() would truncate 3.5 to 3, answering a question nobody asked.
  4268. raise _refuse(not_a_number)
  4269. if value < low or value > high:
  4270. raise _refuse(f"{key} must be between {low} and {high}")
  4271. return value
  4272. def _timestamp_arg(args: dict, key: str) -> datetime | None:
  4273. """An ISO-8601 tool argument as a datetime, or a refusal.
  4274. Search bounds are the first date arguments these tools take, so they get
  4275. the same treatment as numbers: an absent value means "no bound", and a
  4276. wrong one is refused rather than silently dropped — a caller who mistyped
  4277. a date is better served by hearing it than by getting an unbounded search.
  4278. A date without a time is midnight, and a value without an offset is read as
  4279. UTC, matching how everything else here treats a bare timestamp.
  4280. """
  4281. raw = args.get(key)
  4282. if raw is None or raw == "":
  4283. return None
  4284. if isinstance(raw, datetime):
  4285. return raw if raw.tzinfo is not None else raw.replace(tzinfo=UTC)
  4286. try:
  4287. parsed = datetime.fromisoformat(str(raw).strip())
  4288. except ValueError as exc:
  4289. raise _refuse(
  4290. f"{key} must be an ISO-8601 date or timestamp, e.g. '2026-01-31' "
  4291. "or '2026-01-31T12:00:00Z'"
  4292. ) from exc
  4293. return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
  4294. def _enum_arg(args: dict, key: str, mapping: dict[str, Any], default: Any) -> Any:
  4295. """A named tool argument resolved through ``mapping``, or a refusal.
  4296. The choices are spelled out in the schema's enum, so an unknown name means
  4297. the caller invented one; picking a default instead would answer a
  4298. different question than the one asked.
  4299. """
  4300. raw = args.get(key)
  4301. if raw is None or raw == "":
  4302. return default
  4303. value = mapping.get(str(raw).strip().lower())
  4304. if value is None:
  4305. raise _refuse(f"{key} must be one of: {', '.join(sorted(mapping))}")
  4306. return value
  4307. @asynccontextmanager
  4308. async def _tool_client(cfg: ChattoConfiguration | None) -> AsyncIterator[ChattoClient]:
  4309. """A short-lived client for one tool call, closed however the call ends.
  4310. Credentials come from the resolved configuration and from nowhere else. A
  4311. tool argument carrying ``base_url`` would send the configured bot token to
  4312. whatever host the caller named, and every message the bot reads is
  4313. something a caller could talk it into repeating.
  4314. """
  4315. if cfg is None:
  4316. raise _refuse("Chatto configuration unavailable")
  4317. token = cfg.token.value or ""
  4318. if not token:
  4319. raise _refuse("Chatto token not configured")
  4320. try:
  4321. client = ChattoClient(
  4322. base_url=cfg.base_url.value or ChattoClient.DEFAULT_BASE_URL, token=token
  4323. )
  4324. except Exception as exc:
  4325. raise _refuse(f"Failed to create Chatto client: {exc}") from exc
  4326. try:
  4327. yield client
  4328. finally:
  4329. try:
  4330. await client.close()
  4331. except Exception as exc: # pragma: no cover — close is best-effort
  4332. logger.debug("Chatto tools: client close failed: %s", exc)
  4333. # Read-tool bounds, named so the schemas and the validation cannot disagree.
  4334. # A chain is walked hop by hop, so its ceiling is a cost bound: each hop is a
  4335. # round trip, and a caller asking for the whole conversation has
  4336. # chatto_get_history to page it. The page size is bounded for the opposite
  4337. # reason — one read must stay inside a model context.
  4338. FOLLOW_REPLY_CHAIN_MAX = 10
  4339. HISTORY_PAGE_SIZE = 20
  4340. HISTORY_PAGE_MAX = 100
  4341. # Read-tool bounds for pinned messages and attachments — one call per page,
  4342. # kept small enough that a model can digest the output without choking.
  4343. PINNED_PAGE_SIZE = 20
  4344. ATTACHMENT_PAGE_SIZE = 40
  4345. # Search pages are bounded the same way, and for the same reason: a hit is
  4346. # something to read, not a dump. The server's own ceiling is 100, and a page
  4347. # may come back short while `next_cursor` is set — stale index hits are dropped
  4348. # after the provider matches them, which is not an error.
  4349. SEARCH_PAGE_SIZE = 20
  4350. SEARCH_PAGE_MAX = 100
  4351. # The model names a search order the way a person would; the proto spells it
  4352. # out. One table maps the two, so the schema's enum and the lookup cannot
  4353. # disagree about what "newest" means.
  4354. _SEARCH_ORDERS = {
  4355. "relevance": MessageSearchOrder.RELEVANCE,
  4356. "newest": MessageSearchOrder.NEWEST,
  4357. "thread_activity": MessageSearchOrder.THREAD_ACTIVITY,
  4358. "thread_created": MessageSearchOrder.THREAD_CREATED,
  4359. }
  4360. _SEARCH_SCOPES = {"followed_threads": MessageSearchScope.FOLLOWED_THREADS}
  4361. _SEARCH_GROUPS = {"thread": MessageSearchGroupBy.THREAD}
  4362. # Why search cannot answer right now, in terms someone can act on. The server
  4363. # returns FAILED_PRECONDITION for "the operator turned this off" and
  4364. # UNAVAILABLE for "the provider is not ready yet" — the second one resolves
  4365. # itself, the first one never does, and the caller should not have to guess
  4366. # which it hit.
  4367. _SEARCH_STATE_HINTS = {
  4368. MessageSearchState.DISABLED: (
  4369. "message search is turned off on this Chatto server; the operator has "
  4370. "to enable it (`search.enabled = true`) and restart"
  4371. ),
  4372. MessageSearchState.STARTING: (
  4373. "the search provider is starting up; try again shortly"
  4374. ),
  4375. MessageSearchState.INDEXING: (
  4376. "the search provider is still building its index from the message "
  4377. "history, so recent results may be missing; try again later"
  4378. ),
  4379. MessageSearchState.DEGRADED: (
  4380. "the search provider is degraded and answering only partially"
  4381. ),
  4382. MessageSearchState.UNAVAILABLE: ("no search provider is reachable for this server"),
  4383. }
  4384. # A self-deleting notice: long enough to read, short enough not to linger.
  4385. # The floor keeps a TTL from deleting a message before anyone sees it; the
  4386. # ceiling keeps a "transient" notice from becoming a day-long fixture.
  4387. EPHEMERAL_TTL_DEFAULT = 60
  4388. EPHEMERAL_TTL_MIN = 5
  4389. EPHEMERAL_TTL_MAX = 3600
  4390. CHATTO_LIST_ROOMS_SCHEMA = {
  4391. "name": "chatto_list_rooms",
  4392. "description": (
  4393. "List the Chatto rooms visible to the bot (channels and DM rooms), with "
  4394. "their room IDs and whether the bot is a member. Check `is_member` before "
  4395. "posting: the bot can see rooms it has not joined, and cannot post in "
  4396. "them. Use this to resolve a channel name to its room ID — e.g. to find "
  4397. "the 'platform:chat_id' address for a cron job's `deliver` target. "
  4398. "Optional `name` filters case-insensitively by substring."
  4399. ),
  4400. "parameters": {
  4401. "type": "object",
  4402. "properties": {
  4403. "name": {
  4404. "type": "string",
  4405. "description": (
  4406. "Optional: case-insensitive substring filter on the room name "
  4407. "(e.g. 'liv' matches 'Liv' and 'Liv-Dev'). Empty lists all rooms."
  4408. ),
  4409. },
  4410. },
  4411. "required": [],
  4412. "additionalProperties": False,
  4413. },
  4414. }
  4415. CHATTO_LIST_ROOM_ATTACHMENTS_SCHEMA = {
  4416. "name": "chatto_list_room_attachments",
  4417. "description": (
  4418. "List the file attachments in a Chatto room (images, documents, etc.). "
  4419. "Returns each attachment's ID, filename, MIME type, size and an optional "
  4420. "thumbnail URL. Optional ``limit`` (default 40) and ``offset`` allow "
  4421. "paginating through large attachment lists."
  4422. ),
  4423. "parameters": {
  4424. "type": "object",
  4425. "properties": {
  4426. "room_id": {
  4427. "type": "string",
  4428. "description": "The Chatto room ID to list attachments in.",
  4429. },
  4430. "room_name": {
  4431. "type": "string",
  4432. "description": (
  4433. "Optional: human-readable room name — one of ``room_id`` or "
  4434. "``room_name`` is required."
  4435. ),
  4436. },
  4437. "limit": {
  4438. "type": "integer",
  4439. "description": (
  4440. f"Maximum attachments to return (default {ATTACHMENT_PAGE_SIZE})."
  4441. ),
  4442. },
  4443. "offset": {
  4444. "type": "integer",
  4445. "description": "Skip this many attachments (for pagination).",
  4446. },
  4447. },
  4448. "required": [],
  4449. "additionalProperties": False,
  4450. },
  4451. }
  4452. CHATTO_LIST_PINNED_MESSAGES_SCHEMA = {
  4453. "name": "chatto_list_pinned_messages",
  4454. "description": (
  4455. "List pinned messages in a Chatto room. Returns each message's event ID, "
  4456. "body, author (user ID and login), and the pin timestamp. Optional "
  4457. "``limit`` (default 20) and ``offset`` allow paginating through long "
  4458. "pin lists."
  4459. ),
  4460. "parameters": {
  4461. "type": "object",
  4462. "properties": {
  4463. "room_id": {
  4464. "type": "string",
  4465. "description": "The Chatto room ID to list pinned messages in.",
  4466. },
  4467. "room_name": {
  4468. "type": "string",
  4469. "description": (
  4470. "Optional: human-readable room name — one of ``room_id`` or "
  4471. "``room_name`` is required."
  4472. ),
  4473. },
  4474. "limit": {
  4475. "type": "integer",
  4476. "description": f"Maximum pinned messages to return (default {PINNED_PAGE_SIZE}).",
  4477. },
  4478. "offset": {
  4479. "type": "integer",
  4480. "description": "Skip this many pinned messages (for pagination).",
  4481. },
  4482. },
  4483. "required": [],
  4484. "additionalProperties": False,
  4485. },
  4486. }
  4487. CHATTO_PIN_MESSAGE_SCHEMA = {
  4488. "name": "chatto_pin_message",
  4489. "description": (
  4490. "Pin or unpin a message in a Chatto room. Use ``pin=true`` to pin a "
  4491. "message (it becomes visible via ``chatto_list_pinned_messages``), or "
  4492. "``pin=false`` to remove an existing pin. Requires the ``event_id`` of "
  4493. "the message to pin."
  4494. ),
  4495. "parameters": {
  4496. "type": "object",
  4497. "properties": {
  4498. "room_id": {
  4499. "type": "string",
  4500. "description": "The Chatto room ID.",
  4501. },
  4502. "room_name": {
  4503. "type": "string",
  4504. "description": (
  4505. "Optional: human-readable room name — one of ``room_id`` or "
  4506. "``room_name`` is required."
  4507. ),
  4508. },
  4509. "event_id": {
  4510. "type": "string",
  4511. "description": "The message event ID to pin or unpin.",
  4512. },
  4513. "pin": {
  4514. "type": "boolean",
  4515. "description": ("True to pin, false to unpin the message."),
  4516. },
  4517. },
  4518. "required": ["event_id", "pin"],
  4519. "additionalProperties": False,
  4520. },
  4521. }
  4522. CHATTO_SET_CUSTOM_STATUS_SCHEMA = {
  4523. "name": "chatto_set_custom_status",
  4524. "description": (
  4525. "Set the bot's custom status in Chatto. Shows an emoji and text next "
  4526. "to the bot name in the client (e.g. 🛠️ processing, ⏳ awaiting review). "
  4527. "Optional ``expires_in_seconds`` auto-clears the status; omit or 0 for "
  4528. "manual clearing."
  4529. ),
  4530. "parameters": {
  4531. "type": "object",
  4532. "properties": {
  4533. "emoji": {
  4534. "type": "string",
  4535. "description": (
  4536. "A single emoji to show next to the status text (e.g. 🛠️, ⏳, 🔴)."
  4537. ),
  4538. },
  4539. "text": {
  4540. "type": "string",
  4541. "description": (
  4542. "The status text to display (e.g. 'processing', 'awaiting review')."
  4543. ),
  4544. },
  4545. "expires_in_seconds": {
  4546. "type": "integer",
  4547. "description": (
  4548. "Optional: auto-clear the status after this many seconds. "
  4549. "Omit or 0 to keep the status until cleared."
  4550. ),
  4551. },
  4552. },
  4553. "required": ["emoji", "text"],
  4554. "additionalProperties": False,
  4555. },
  4556. }
  4557. CHATTO_DELETE_CUSTOM_STATUS_SCHEMA = {
  4558. "name": "chatto_delete_custom_status",
  4559. "description": ("Clear the bot's custom status, reverting to no status display."),
  4560. "parameters": {
  4561. "type": "object",
  4562. "properties": {},
  4563. "required": [],
  4564. "additionalProperties": False,
  4565. },
  4566. }
  4567. CHATTO_SEND_DM_SCHEMA = {
  4568. "name": "chatto_send_dm",
  4569. "description": (
  4570. "Send a text message as a **Direct Message** to another Chatto user. "
  4571. "Looks up the user by `user_login` or `user_id` and posts into the DM "
  4572. "room you already have with them. Returns success with the room_id "
  4573. "and message_ids, or an error."
  4574. ),
  4575. "parameters": {
  4576. "type": "object",
  4577. "properties": {
  4578. "user_login": {
  4579. "type": "string",
  4580. "description": (
  4581. "The Chatto login name of the recipient "
  4582. "(e.g. 'nickk'). Exactly one of `user_login` or `user_id` is required."
  4583. ),
  4584. },
  4585. "user_id": {
  4586. "type": "string",
  4587. "description": (
  4588. "The Chatto user ID of the recipient "
  4589. "(e.g. 'Uxxxxxxxx'). Exactly one of `user_login` or `user_id` is required."
  4590. ),
  4591. },
  4592. "message": {
  4593. "type": "string",
  4594. "description": "The message text to send (markdown supported).",
  4595. },
  4596. },
  4597. "required": ["message"],
  4598. "additionalProperties": False,
  4599. },
  4600. }
  4601. CHATTO_FETCH_LINK_PREVIEW_SCHEMA = {
  4602. "name": "chatto_fetch_link_preview",
  4603. "description": (
  4604. "Fetch an OpenGraph link preview for a URL. Returns title, description, "
  4605. "image URL and other metadata that Chatto's server would show when "
  4606. "rendering the link in a message. Passes through whatever metadata the "
  4607. "target site provides."
  4608. ),
  4609. "parameters": {
  4610. "type": "object",
  4611. "properties": {
  4612. "url": {
  4613. "type": "string",
  4614. "description": (
  4615. "The URL to fetch a preview for (e.g. 'https://example.com')."
  4616. ),
  4617. },
  4618. },
  4619. "required": ["url"],
  4620. "additionalProperties": False,
  4621. },
  4622. }
  4623. CHATTO_SEND_ROOM_SCHEMA = {
  4624. "name": "chatto_send_room",
  4625. "description": (
  4626. "Send a text message to a Chatto **room** (channel or DM room) "
  4627. "by its room ID or room name. Channels the bot is configured to "
  4628. "answer in only — a room on neither mention list stays read-only. "
  4629. "Returns success with the message_ids, or an error."
  4630. ),
  4631. "parameters": {
  4632. "type": "object",
  4633. "properties": {
  4634. "room_id": {
  4635. "type": "string",
  4636. "description": (
  4637. "The Chatto room ID of the destination "
  4638. "(e.g. 'RbmwiHk4vs9a3Ql'). Exactly one of `room_id` or `room_name` is required."
  4639. ),
  4640. },
  4641. "room_name": {
  4642. "type": "string",
  4643. "description": (
  4644. "The display name of the room (case-insensitive). Exactly one "
  4645. "of `room_id` or `room_name` is required. If several rooms "
  4646. "share the name, the call returns their IDs instead of guessing."
  4647. ),
  4648. },
  4649. "message": {
  4650. "type": "string",
  4651. "description": "The message text to send (markdown supported).",
  4652. },
  4653. "thread_root_event_id": {
  4654. "type": "string",
  4655. "description": (
  4656. "Optional: event ID of the thread-root message. When given, "
  4657. "this message is posted INSIDE that thread, which has to be "
  4658. "a thread root of the destination room. Mutually exclusive "
  4659. "with `create_thread`."
  4660. ),
  4661. },
  4662. "create_thread": {
  4663. "type": "boolean",
  4664. "description": (
  4665. "Optional: post this message as the ROOT of a new thread "
  4666. "(default false = normal message). Only for channel rooms. "
  4667. "Mutually exclusive with `thread_root_event_id`."
  4668. ),
  4669. },
  4670. },
  4671. "required": ["message"],
  4672. "additionalProperties": False,
  4673. },
  4674. }
  4675. CHATTO_SEND_EPHEMERAL_SCHEMA = {
  4676. "name": "chatto_send_ephemeral",
  4677. "description": (
  4678. "Send a text notice to a Chatto room that deletes itself after a TTL. "
  4679. "Use it for progress or status updates that should not stay in the "
  4680. "timeline. Same room rules as chatto_send_room: a channel the bot is "
  4681. "configured to answer in only. Returns the message_ids and the TTL, or "
  4682. "an error. Deletion is best-effort: a gateway restart before the TTL "
  4683. "expires leaves the notice in the room."
  4684. ),
  4685. "parameters": {
  4686. "type": "object",
  4687. "properties": {
  4688. "room_id": {
  4689. "type": "string",
  4690. "description": (
  4691. "The Chatto room ID of the destination. Exactly one of "
  4692. "`room_id` or `room_name` is required."
  4693. ),
  4694. },
  4695. "room_name": {
  4696. "type": "string",
  4697. "description": (
  4698. "The display name of the room (case-insensitive). Exactly one "
  4699. "of `room_id` or `room_name` is required. If several rooms "
  4700. "share the name, the call returns their IDs instead of guessing."
  4701. ),
  4702. },
  4703. "message": {
  4704. "type": "string",
  4705. "description": "The notice text (markdown supported).",
  4706. },
  4707. "ttl_seconds": {
  4708. "type": "integer",
  4709. "description": (
  4710. f"Seconds until the notice is deleted (default "
  4711. f"{EPHEMERAL_TTL_DEFAULT}, min {EPHEMERAL_TTL_MIN}, "
  4712. f"max {EPHEMERAL_TTL_MAX})."
  4713. ),
  4714. },
  4715. },
  4716. "required": ["message"],
  4717. "additionalProperties": False,
  4718. },
  4719. }
  4720. CHATTO_MARK_THREAD_AS_READ_SCHEMA = {
  4721. "name": "chatto_mark_thread_as_read",
  4722. "description": (
  4723. "Mark a thread as read for the bot. This updates the server's read "
  4724. "marker so Chatto clients show the thread as read. Useful after the bot "
  4725. "has processed a thread's full context."
  4726. ),
  4727. "parameters": {
  4728. "type": "object",
  4729. "properties": {
  4730. "room_id": {
  4731. "type": "string",
  4732. "description": "The Chatto room ID of the thread.",
  4733. },
  4734. "room_name": {
  4735. "type": "string",
  4736. "description": (
  4737. "Optional: room name — one of ``room_id`` or ``room_name`` is required."
  4738. ),
  4739. },
  4740. "thread_root_event_id": {
  4741. "type": "string",
  4742. "description": ("The event ID of the thread root message."),
  4743. },
  4744. },
  4745. "required": ["thread_root_event_id"],
  4746. "additionalProperties": False,
  4747. },
  4748. }
  4749. CHATTO_GET_MESSAGE_SCHEMA = {
  4750. "name": "chatto_get_message",
  4751. "description": (
  4752. "Read one or more Chatto messages by event ID, with all their data: "
  4753. "body, author (user ID + login), timestamps, reply/thread references "
  4754. "(in_reply_to, thread_root_event_id), attachments, reactions, pinned "
  4755. "and deleted status. Use it to resolve a `reply_to=`/`in_reply_to` "
  4756. "reference or any other event ID mentioned in a message. "
  4757. "`follow_reply_chain` (0-10) additionally walks the in_reply_to chain "
  4758. "backwards and returns the ancestor messages oldest-first; it applies to "
  4759. "a single `event_id` and is refused with `event_ids`. `event_ids` "
  4760. "fetches several messages in one call, answered in the order asked for "
  4761. "(then `event_id` is refused)."
  4762. ),
  4763. "parameters": {
  4764. "type": "object",
  4765. "properties": {
  4766. "room_id": {
  4767. "type": "string",
  4768. "description": (
  4769. "The Chatto room ID the message lives in "
  4770. "(e.g. 'RbmwiHk4vs9a3Ql'). Exactly one of `room_id` or "
  4771. "`room_name` is required."
  4772. ),
  4773. },
  4774. "room_name": {
  4775. "type": "string",
  4776. "description": (
  4777. "The room's display name (case-insensitive). Exactly one of "
  4778. "`room_id` or `room_name` is required; ambiguous names are "
  4779. "refused with the candidate IDs."
  4780. ),
  4781. },
  4782. "event_id": {
  4783. "type": "string",
  4784. "description": (
  4785. "The event ID of the message to read (e.g. 'EM0D7tFdvd14EXS'). "
  4786. "Exactly one of `event_id` or `event_ids` is required."
  4787. ),
  4788. },
  4789. "event_ids": {
  4790. "type": "array",
  4791. "items": {"type": "string"},
  4792. "description": (
  4793. "Several event IDs to read in one call. Mutually exclusive "
  4794. "with `event_id`."
  4795. ),
  4796. },
  4797. "follow_reply_chain": {
  4798. "type": "integer",
  4799. "description": (
  4800. "How many in_reply_to ancestors to resolve, 0-10 "
  4801. "(default 0 = do not follow). Single `event_id` only."
  4802. ),
  4803. },
  4804. },
  4805. "required": [],
  4806. "additionalProperties": False,
  4807. },
  4808. }
  4809. CHATTO_LIST_ROOM_GROUPS_SCHEMA = {
  4810. "name": "chatto_list_room_groups",
  4811. "description": (
  4812. "List room groups as configured on the Chatto server. Each group has an "
  4813. "ID, name, description, list of rooms, and optional sidebar links. "
  4814. "Useful for browsing the server's room organisation."
  4815. ),
  4816. "parameters": {
  4817. "type": "object",
  4818. "properties": {},
  4819. "required": [],
  4820. "additionalProperties": False,
  4821. },
  4822. }
  4823. CHATTO_GET_HISTORY_SCHEMA = {
  4824. "name": "chatto_get_history",
  4825. "description": (
  4826. "Read the most recent messages of a Chatto room, or of one thread in "
  4827. "it, oldest-first. Use it for context: what was said before a message "
  4828. "the bot is about to answer or reference. With `thread_root_event_id` "
  4829. "the thread's events are read instead of the room timeline; the root "
  4830. "has to belong to the room and BE a root, like in chatto_send_room. "
  4831. "`limit` (1-100, default 20) bounds the page; `has_older` says whether "
  4832. "older history exists. To read further back, pass the previous "
  4833. "result's `start_cursor` as `before` — one call reads one page."
  4834. ),
  4835. "parameters": {
  4836. "type": "object",
  4837. "properties": {
  4838. "room_id": {
  4839. "type": "string",
  4840. "description": (
  4841. "The Chatto room ID to read (e.g. 'RbmwiHk4vs9a3Ql'). "
  4842. "Exactly one of `room_id` or `room_name` is required."
  4843. ),
  4844. },
  4845. "room_name": {
  4846. "type": "string",
  4847. "description": (
  4848. "The room's display name (case-insensitive). Exactly one of "
  4849. "`room_id` or `room_name` is required; ambiguous names are "
  4850. "refused with the candidate IDs."
  4851. ),
  4852. },
  4853. "thread_root_event_id": {
  4854. "type": "string",
  4855. "description": (
  4856. "Optional: read this thread's events instead of the room "
  4857. "timeline. The ID must be a thread ROOT in this room."
  4858. ),
  4859. },
  4860. "limit": {
  4861. "type": "integer",
  4862. "description": (
  4863. "Maximum number of messages to return, 1-100 (default 20)."
  4864. ),
  4865. },
  4866. "before": {
  4867. "type": "string",
  4868. "description": (
  4869. "Optional: page backwards. Pass the `start_cursor` of the "
  4870. "previous result — cursors are opaque positions, not event "
  4871. "IDs. Mutually exclusive with `after`."
  4872. ),
  4873. },
  4874. "after": {
  4875. "type": "string",
  4876. "description": (
  4877. "Optional: page forwards. Pass the `end_cursor` of the "
  4878. "previous result. Mutually exclusive with `before`."
  4879. ),
  4880. },
  4881. },
  4882. "required": [],
  4883. "additionalProperties": False,
  4884. },
  4885. }
  4886. CHATTO_SEARCH_MESSAGES_SCHEMA = {
  4887. "name": "chatto_search_messages",
  4888. "description": (
  4889. "Full-text search over Chatto messages the bot can read. Use it to find "
  4890. "something said earlier when you do not know which room, thread or day: "
  4891. "`chatto_get_history` reads a window, this finds a needle. Search is a "
  4892. "server feature the operator has to enable; when it is off or still "
  4893. "building its index, the answer says so instead of reporting no "
  4894. 'matches. Query syntax: words are required terms, "quoted text" is an '
  4895. "exact phrase, `AND` separates terms, and `in:`, `from:`, `before:`, "
  4896. "`after:`, `has:attachment` are filters. Scope it with `room_id`/"
  4897. "`room_name`, `author_id` or the time bounds; `group_by: thread` "
  4898. "answers one row per matching thread instead of per message."
  4899. ),
  4900. "parameters": {
  4901. "type": "object",
  4902. "properties": {
  4903. "query": {
  4904. "type": "string",
  4905. "description": (
  4906. "Required search expression. Words are required terms "
  4907. '(all must match), "a quoted phrase" matches exactly, and '
  4908. "`AND` may join terms. Filters: `in:room-name`, "
  4909. "`from:user-login`, `before:2026-03-01`, "
  4910. "`after:2026-01-01`, `has:attachment`. A filter may be used "
  4911. "without a word or phrase."
  4912. ),
  4913. },
  4914. "room_id": {
  4915. "type": "string",
  4916. "description": (
  4917. "Optional: search only this room (e.g. 'RbmwiHk4vs9a3Ql'). "
  4918. "Mutually exclusive with `room_name`. Without either, the "
  4919. "search covers every room the bot is a member of."
  4920. ),
  4921. },
  4922. "room_name": {
  4923. "type": "string",
  4924. "description": (
  4925. "Optional: search only the room with this display name "
  4926. "(case-insensitive). Mutually exclusive with `room_id`; "
  4927. "ambiguous names are refused with the candidate IDs."
  4928. ),
  4929. },
  4930. "author_id": {
  4931. "type": "string",
  4932. "description": (
  4933. "Optional: only messages posted by this Chatto user ID. To "
  4934. "filter by login instead, put `from:<login>` inside "
  4935. "`query`."
  4936. ),
  4937. },
  4938. "created_after": {
  4939. "type": "string",
  4940. "description": (
  4941. "Optional ISO-8601 lower bound on posting time, exclusive "
  4942. "(e.g. '2026-01-31' or '2026-01-31T12:00:00Z'). When "
  4943. "`query` also carries `after:`, the stricter bound wins."
  4944. ),
  4945. },
  4946. "created_before": {
  4947. "type": "string",
  4948. "description": (
  4949. "Optional ISO-8601 upper bound on posting time, exclusive. "
  4950. "When `query` also carries `before:`, the stricter bound "
  4951. "wins."
  4952. ),
  4953. },
  4954. "has_attachments": {
  4955. "type": "boolean",
  4956. "description": (
  4957. "Optional: true returns only messages that currently have "
  4958. "attachments."
  4959. ),
  4960. },
  4961. "order": {
  4962. "type": "string",
  4963. "enum": [
  4964. "relevance",
  4965. "newest",
  4966. "thread_activity",
  4967. "thread_created",
  4968. ],
  4969. "description": (
  4970. "Result order (default relevance). `thread_activity` and "
  4971. "`thread_created` require `group_by: thread`."
  4972. ),
  4973. },
  4974. "group_by": {
  4975. "type": "string",
  4976. "enum": ["thread"],
  4977. "description": (
  4978. "Optional: with `thread`, return one row per matching "
  4979. "thread instead of one per message, with the thread's root, "
  4980. "reply count and latest reply."
  4981. ),
  4982. },
  4983. "scope": {
  4984. "type": "string",
  4985. "enum": ["followed_threads"],
  4986. "description": (
  4987. "Optional: with `followed_threads`, search only threads the "
  4988. "bot follows. Combine with `group_by: thread` for a thread "
  4989. "list."
  4990. ),
  4991. },
  4992. "limit": {
  4993. "type": "integer",
  4994. "description": (
  4995. "Maximum results per page, 1-100 (default 20). The page is "
  4996. "counted in messages, or in threads when `group_by` is "
  4997. "`thread`."
  4998. ),
  4999. },
  5000. "cursor": {
  5001. "type": "string",
  5002. "description": (
  5003. "Opaque `next_cursor` from a previous call, for the next "
  5004. "page. Bound to this caller and to every other query field, "
  5005. "so repeat the same query with it. Results come from a live "
  5006. "index: a page may repeat or omit a hit that moved while "
  5007. "paging."
  5008. ),
  5009. },
  5010. },
  5011. "required": ["query"],
  5012. "additionalProperties": False,
  5013. },
  5014. }
  5015. def _chatto_config_for_tools() -> ChattoConfiguration | None:
  5016. """Resolve the Chatto configuration for plugin tool handlers.
  5017. Two tiers, most specific first:
  5018. 1. The snapshot ``hermes_validate_config`` published for *this* profile — the
  5019. authoritative one in a running gateway.
  5020. 2. A fresh read of config.yaml plus the serving profile's own secrets, for
  5021. the cron and standalone sessions where the gateway load hooks never ran
  5022. and the dotenv residue has been stripped from ``os.environ``. Mirrors how
  5023. the built-in send_message tool resolves its pconfig
  5024. (tools/send_message_tool.py).
  5025. Both tiers are keyed by the serving profile, so a multiplexed gateway hands
  5026. each profile its own credentials rather than whichever one was served last.
  5027. Returns ``None`` when neither tier yields a configuration; the caller
  5028. reports that rather than guessing at credentials.
  5029. """
  5030. scope_key = _profile_scope_key()
  5031. snapshot = _resolved_chatto_configs.get(scope_key)
  5032. if snapshot is not None:
  5033. return snapshot
  5034. # config.yaml's own ``extra`` block, so a deployment configured there — and
  5035. # nowhere in .env — is honoured outside the gateway process too.
  5036. try:
  5037. from gateway.config import Platform as GatewayPlatform
  5038. from gateway.config import load_gateway_config
  5039. pconfig = load_gateway_config().platforms.get(
  5040. GatewayPlatform(ChattoConstants.PLATFORM_NAME)
  5041. )
  5042. resolved = ChattoConfiguration(pconfig=_pconfig_or_empty(pconfig))
  5043. except Exception as exc:
  5044. logger.warning("Chatto tools: could not read gateway config: %s", exc)
  5045. return None
  5046. # In a fresh cron scope the dotenv residue is stripped from os.environ, so
  5047. # ChattoConfiguration's env layer sees nothing. The secrets then come from
  5048. # the scope Hermes installed for the profile being served when there is one —
  5049. # that mapping is that profile's authoritative secret set, and rebuilding
  5050. # one from the launch home would answer with another profile's credentials.
  5051. # With no scope installed (CLI, bare standalone sender) the profile's own
  5052. # .env is the right source, and build_profile_secret_scope reads it
  5053. # directly in gateway, cron and CLI contexts alike.
  5054. try:
  5055. from agent.secret_scope import current_secret_scope
  5056. profile_secrets = current_secret_scope()
  5057. if profile_secrets is None:
  5058. from agent.secret_scope import build_profile_secret_scope
  5059. from hermes_constants import get_hermes_home
  5060. profile_secrets = dict(build_profile_secret_scope(get_hermes_home()))
  5061. except Exception as exc:
  5062. logger.warning("Chatto tools: profile secret scope build failed: %s", exc)
  5063. profile_secrets = {}
  5064. resolved.overlay_profile_secrets(profile_secrets)
  5065. # Cache only a configuration that can actually send. Caching a tokenless one
  5066. # would pin this failure for the life of the process: the next call in a
  5067. # properly scoped context would be served the degraded config and keep
  5068. # reporting "token not configured" long after the scope came back.
  5069. if resolved.token.value:
  5070. _resolved_chatto_configs[scope_key] = resolved
  5071. return resolved
  5072. def _parse_room_toolsets(
  5073. entries: Iterable[str],
  5074. ) -> tuple[dict[str, list[str]], list[str]]:
  5075. """Split ``room_id:toolset`` entries into per-room toolset lists.
  5076. Returns the mapping plus the entries that could not be read. Several
  5077. entries may name the same room; they accumulate in the order given, which
  5078. is what lets a room keep more than one toolset without inventing a nested
  5079. separator inside a comma-separated list. Malformed entries are reported
  5080. rather than raised: startup validation refuses the config, and a running
  5081. gateway must not die on a typo it can ignore.
  5082. """
  5083. by_room: dict[str, list[str]] = {}
  5084. malformed: list[str] = []
  5085. for raw in entries:
  5086. entry = str(raw).strip()
  5087. room_id, _, toolset = entry.partition(":")
  5088. room_id, toolset = room_id.strip(), toolset.strip()
  5089. if not room_id or not toolset:
  5090. malformed.append(entry)
  5091. continue
  5092. toolsets = by_room.setdefault(room_id, [])
  5093. if toolset not in toolsets:
  5094. toolsets.append(toolset)
  5095. return by_room, malformed
  5096. def _room_answers_in(
  5097. cfg: ChattoConfiguration | None, room_id: str, kind: RoomKind | None
  5098. ) -> bool:
  5099. """Whether the bot takes part in this room: answers there, and may post.
  5100. The single definition of that question, on purpose. It answers for two
  5101. callers whose disagreement would be a bug the user cannot see:
  5102. - ``ChattoAdapter._answers_in_room``, the *inbound* gate — whether a
  5103. message here reaches the agent at all
  5104. - ``_room_is_writable``, the *outbound* gate on the send tools, so a tool
  5105. cannot post into a room that would never have answered
  5106. Chatto knows only DMs and channels, so the split is ``kind == DM``: a DM
  5107. always answers (``/join`` must stay reachable), and every other kind —
  5108. channel, an unknown kind (which is how servers that never set ``kind`` show
  5109. up), or a room the adapter has not resolved yet, so ``kind`` is None —
  5110. opts in through one of the two mention lists. The lists are mutually
  5111. exclusive by validation; should contradictory config reach a running adapter
  5112. anyway, optional beats require, because answering a room is safer than
  5113. muting it. A ``cfg`` of None means no configuration could be resolved at
  5114. all, and then nothing but a DM qualifies.
  5115. """
  5116. if kind == RoomKind.DM:
  5117. return True
  5118. if cfg is None:
  5119. return False
  5120. if room_id in cfg.optional_mention_rooms.value:
  5121. return True
  5122. return room_id in cfg.require_mention_rooms.value
  5123. def _pconfig_or_empty(pconfig: PlatformConfig | None) -> PlatformConfig:
  5124. """The Chatto PlatformConfig from config.yaml, or an empty stand-in."""
  5125. if pconfig is not None:
  5126. return pconfig
  5127. from gateway.config import PlatformConfig as GatewayPlatformConfig
  5128. return GatewayPlatformConfig(enabled=True, extra={})
  5129. def _room_is_writable(cfg: ChattoConfiguration | None, room: Room) -> bool:
  5130. """Whether the bot may post into this room on its own initiative.
  5131. Delegates to ``_room_answers_in`` so the outbound gate is the *same*
  5132. function as the inbound one: a room that would never be answered must not
  5133. be postable, and two copies of that rule would drift apart until the send
  5134. tool became a way around the read-only promise.
  5135. """
  5136. return _room_answers_in(cfg, room.id, room.kind)
  5137. def _not_joined_refusal(room: Room, action: str) -> _ToolRefusal:
  5138. """The refusal for a room the bot can see but has not joined.
  5139. ``action`` names what the caller wanted to do there — "post there", "read
  5140. its history there" — because the remedy is identical for both while the
  5141. symptom is not, and a read that reports a sending problem sends the reader
  5142. looking in the wrong place. The room kinds differ in the remedy: giving a
  5143. channel the DM remedy sends the user down a path that cannot work, since a
  5144. direct message to the bot is not how you get it into a channel.
  5145. The test is on ``DM`` rather than on ``CHANNEL`` on purpose: a server that
  5146. never sets ``kind`` reports ``UNSPECIFIED``, and this plugin counts an unknown
  5147. kind as a channel everywhere else (``_room_answers_in``, ``_refresh_rooms``).
  5148. Keying on ``CHANNEL`` would hand exactly the advice this function exists to
  5149. avoid to every self-hosted server on an older or looser build.
  5150. """
  5151. remedy = (
  5152. "Have someone start a DM with the bot account"
  5153. if room.kind == RoomKind.DM
  5154. else f"Invite the bot account in Chatto, or DM it `/join {room.id}`"
  5155. )
  5156. return _refuse(
  5157. f"Room '{room.name or room.id}' ({room.id}) is not one the bot has "
  5158. f"joined, so it cannot {action}. {remedy}, then try again."
  5159. )
  5160. def _read_only_room_refusal(room_label: str) -> _ToolRefusal:
  5161. """The refusal a read-only room earns, naming where to opt it in.
  5162. This reply is where an operator copies the room ID from, so it spells both
  5163. env vars out verbatim.
  5164. """
  5165. return _refuse(
  5166. f"Room '{room_label}' is configured read-only: the bot neither answers "
  5167. "there nor posts to it on its own initiative. To allow that, add the "
  5168. f"room ID to {ChattoConfiguration.require_mention_rooms.env_name} (only "
  5169. f"answers when addressed) or {ChattoConfiguration.optional_mention_rooms.env_name} "
  5170. "(answers everything) in ~/.hermes/.env, and restart the gateway."
  5171. )
  5172. class _ChunkDelivery(NamedTuple):
  5173. """What a split send actually put into a room.
  5174. ``error`` is the exception that stopped the batch, if any: the chunks in
  5175. ``message_ids`` did go out and must not be resent. Each caller shapes this
  5176. into its own result contract — a ``SendResult`` for the adapter, a refusal
  5177. for the tools — because those are genuinely different contracts; the
  5178. *sending* is not. ``chunks_total`` counts what the split produced, so a
  5179. caller can report "got 1 of 3 out" without re-deriving the split.
  5180. """
  5181. message_ids: list[str]
  5182. root_event_id: str
  5183. error: Exception | None
  5184. chunks_total: int
  5185. async def _deliver_chunks(
  5186. client: ChattoClient,
  5187. room_id: str,
  5188. message: str,
  5189. *,
  5190. thread_root_event_id: str = "",
  5191. create_thread: bool = False,
  5192. on_posted: Callable[[str], None] | None = None,
  5193. ) -> _ChunkDelivery:
  5194. """Post a message split at the server limit, stopping at the first failure.
  5195. One implementation for both send paths, because the decisions are the same
  5196. and a copy of each drifts: split at ``SPLIT_THRESHOLD`` like every other
  5197. send, and route a split answer as *one* answer — chunk 1 opens a thread
  5198. (``create_thread``) or joins the one passed in, and every later chunk
  5199. carries that root, so a long reply does not scatter across the timeline.
  5200. ``on_posted`` is the adapter's ``_mark_seen``: the tools have no dedup state
  5201. to keep, the adapter must not treat its own output as unread input. The
  5202. first failure stops the batch and is returned rather than raised — the
  5203. caller knows better than this function what a partial send means to it, and
  5204. what to call the exception (``ChattoError`` is a server failure, anything
  5205. else is a bug here).
  5206. """
  5207. normalised = _normalise_outbound_text(message)
  5208. chunks = BasePlatformAdapter.truncate_message(
  5209. normalised, ChattoConstants.SPLIT_THRESHOLD
  5210. )
  5211. message_ids: list[str] = []
  5212. root_id = thread_root_event_id
  5213. for chunk in chunks:
  5214. try:
  5215. posted = await client.post_message(
  5216. room_id=room_id, body=chunk, thread_root_event_id=root_id
  5217. )
  5218. except Exception as exc:
  5219. return _ChunkDelivery(message_ids, root_id, exc, len(chunks))
  5220. message_ids.append(posted.id)
  5221. if on_posted is not None:
  5222. on_posted(posted.id)
  5223. if create_thread and not root_id:
  5224. root_id = posted.id
  5225. return _ChunkDelivery(message_ids, root_id, None, len(chunks))
  5226. async def _post_chunks(
  5227. client: ChattoClient,
  5228. room_id: str,
  5229. message: str,
  5230. *,
  5231. thread_root_event_id: str = "",
  5232. create_thread: bool = False,
  5233. ) -> tuple[list[str], str]:
  5234. """Post a message through ``_deliver_chunks`` as a tool result. ``(ids, root)``.
  5235. A chunk that fails leaves the earlier ones delivered, so this refuses with
  5236. exactly what went out: calling a half-delivered send a plain failure
  5237. invites an agent to retry and duplicate what the room already has.
  5238. """
  5239. delivery = await _deliver_chunks(
  5240. client,
  5241. room_id,
  5242. message,
  5243. thread_root_event_id=thread_root_event_id,
  5244. create_thread=create_thread,
  5245. )
  5246. if delivery.error is not None:
  5247. # Blame the server only for a server error. chattolib maps every
  5248. # transport failure to ChattoError, so anything else is a bug on our
  5249. # side — calling that "Chatto API error" would send an operator hunting
  5250. # the wrong component.
  5251. cause = (
  5252. "Chatto API error"
  5253. if isinstance(delivery.error, ChattoError)
  5254. else "Internal plugin error"
  5255. )
  5256. raise _refuse(
  5257. f"{cause} on chunk {len(delivery.message_ids) + 1}/"
  5258. f"{delivery.chunks_total}: {delivery.error}",
  5259. # partial marks a half-delivered send; the caller must not
  5260. # resend it from the top without knowing about these chunks.
  5261. partial=bool(delivery.message_ids),
  5262. room_id=room_id,
  5263. message_ids=delivery.message_ids,
  5264. chunks_sent=len(delivery.message_ids),
  5265. chunks_total=delivery.chunks_total,
  5266. ) from delivery.error
  5267. return delivery.message_ids, delivery.root_event_id
  5268. async def _find_user_by_login(client: ChattoClient, user_login: str) -> tuple[str, str]:
  5269. """Find a user among the members of our DM rooms, ``(user_id, login)``.
  5270. Both are empty when no room yields the login. Only a person can start a DM,
  5271. so a DM room is the only place a deliverable recipient can be — scanning
  5272. the channels the bot sits in would cost one member RPC per room and could
  5273. resolve a login whose DM does not exist yet. A bot cannot read the
  5274. server-wide user directory either: that needs admin rights.
  5275. Every DM room is searched, including one whose membership the directory
  5276. left unreported — that field is optional, and skipping such a room would
  5277. make its login unfindable while the DM room sits right there.
  5278. """
  5279. for rws in await client.list_rooms():
  5280. room = rws.room
  5281. if room is None or room.kind != RoomKind.DM:
  5282. continue
  5283. try:
  5284. member_ids, _ = await client.list_room_members(room.id, search=user_login)
  5285. except ChattoError as exc:
  5286. # A room we cannot enumerate must not abort the search over the
  5287. # remaining ones.
  5288. logger.debug("Chatto tools: member search in %s failed: %s", room.id, exc)
  5289. continue
  5290. if not member_ids:
  5291. continue
  5292. for member in await client.batch_get_room_members(room.id, member_ids):
  5293. user = member.user
  5294. if (
  5295. user is not None
  5296. and user.login
  5297. and user.login.casefold() == user_login.casefold()
  5298. ):
  5299. return user.id, user.login
  5300. return "", ""
  5301. async def _find_dm_room(
  5302. client: ChattoClient, our_id: str, other_id: str
  5303. ) -> Room | None:
  5304. """The DM room between two users, or None when there is none yet.
  5305. Membership is read from the room object the directory already returned, and
  5306. only falls back to a ListMembers RPC when that came back empty:
  5307. ``member_user_ids`` is not among the fields the ListRooms documentation
  5308. lists for ``RoomWithViewerState``, so a server is free to leave it
  5309. unpopulated — and a DM room we can see plainly exists, whatever the
  5310. directory said about who is in it. The fallback costs one RPC per DM room
  5311. and only on servers that need it.
  5312. """
  5313. for rws in await client.list_rooms():
  5314. room = rws.room
  5315. if room is None or room.kind != RoomKind.DM:
  5316. continue
  5317. if rws.member_user_ids:
  5318. if other_id in rws.member_user_ids and our_id in rws.member_user_ids:
  5319. return room
  5320. continue
  5321. try:
  5322. member_ids, _page = await client.list_room_members(room.id)
  5323. except ChattoError as exc:
  5324. # An unreadable room cannot be the one we want, but it must not
  5325. # abort the search over the remaining ones.
  5326. logger.debug("Chatto tools: members of DM %s unreadable: %s", room.id, exc)
  5327. continue
  5328. if other_id in member_ids and our_id in member_ids:
  5329. return room
  5330. return None
  5331. class _ResolvedRoom(NamedTuple):
  5332. """A room the send path resolved, plus whether the bot belongs to it.
  5333. Membership travels with the room because the directory answers a broader
  5334. question than the send path can use: a room the bot can *see* is not one it
  5335. can *post in* (ListRooms returns visible channels, membership or room.list
  5336. permission). Splitting that into two lookups would be a second chance to
  5337. disagree with the state the first one already carried.
  5338. """
  5339. room: Room
  5340. is_member: bool
  5341. async def _resolve_room(
  5342. client: ChattoClient, room_id: str, room_name: str
  5343. ) -> _ResolvedRoom:
  5344. """The destination room, by ID or by name.
  5345. A name is not unique on Chatto — two room groups may both hold an "Ops" —
  5346. and delivering to whichever the directory listed first is not a choice
  5347. anyone made, so an ambiguous name asks for the ID instead.
  5348. """
  5349. if room_id:
  5350. room_viewer_state = await client.get_room(room_id)
  5351. if room_viewer_state is None or room_viewer_state.room is None:
  5352. raise _refuse(
  5353. f"Room {room_id} was not found, or the bot cannot see it. "
  5354. "Use chatto_list_rooms to look up a room ID."
  5355. )
  5356. return _ResolvedRoom(
  5357. room_viewer_state.room, room_viewer_state.viewer_state.is_member
  5358. )
  5359. matches = [
  5360. _ResolvedRoom(rws.room, rws.viewer_state.is_member)
  5361. for rws in await client.list_rooms()
  5362. if rws.room is not None
  5363. and (rws.room.name or "").casefold() == room_name.casefold()
  5364. ]
  5365. if not matches:
  5366. raise _refuse(
  5367. f"Room not found: {room_name}. Use chatto_list_rooms to see the available names."
  5368. )
  5369. if len(matches) > 1:
  5370. candidates = ", ".join(
  5371. f"{match.room.id} ('{match.room.name}')" for match in matches
  5372. )
  5373. raise _refuse(
  5374. f"Room name '{room_name}' is ambiguous — {len(matches)} rooms carry it: "
  5375. f"{candidates}. Pass the room_id instead."
  5376. )
  5377. return matches[0]
  5378. async def _resolve_thread_root(
  5379. client: ChattoClient, room: Room, event_id: str
  5380. ) -> Message:
  5381. """The thread root a tool was pointed at, or a refusal saying why not.
  5382. Both tools that take a ``thread_root_event_id`` — posting into one and
  5383. reading one — resolve it here, because two copies of "is this a root?" is
  5384. one too many: they drift, and the drift shows up as two tools disagreeing
  5385. about the same event ID.
  5386. Two things have to hold. The message has to exist in this room (a root from
  5387. another room would attach a thread to the wrong conversation), and it has
  5388. to BE a root (a reply's ID names no thread, so following it lands nowhere).
  5389. """
  5390. root = await client.get_message(room.id, event_id)
  5391. if root is None:
  5392. raise _refuse(
  5393. f"No message {event_id} in room {room.id}. It has to be an event ID "
  5394. f"from this room — chatto_get_history lists them."
  5395. )
  5396. if root.thread_root_event_id:
  5397. raise _refuse(
  5398. f"Message {event_id} is a reply inside thread "
  5399. f"{root.thread_root_event_id}, not a thread root. Pass that "
  5400. "thread's root ID instead."
  5401. )
  5402. return root
  5403. async def _send_dm(args: dict) -> str:
  5404. """Resolve the recipient, find the DM room, post. See _handle_chatto_send_dm."""
  5405. user_login = args.get("user_login") or ""
  5406. user_id = args.get("user_id") or ""
  5407. message = args.get("message") or ""
  5408. if not message:
  5409. raise _refuse("message is required")
  5410. if not user_login and not user_id:
  5411. raise _refuse("Exactly one of user_login or user_id is required")
  5412. async with _tool_client(_chatto_config_for_tools()) as client:
  5413. # A bot cannot read the server-wide user directory (that needs admin
  5414. # rights), so a login is resolved among the members of shared rooms.
  5415. target_user_id = user_id
  5416. target_login = user_login
  5417. if not target_user_id:
  5418. target_user_id, target_login = await _find_user_by_login(client, user_login)
  5419. if not target_user_id:
  5420. raise _refuse(f"User not found: {user_login} shares no DM with the bot")
  5421. # Only people may start a DM (Chatto permissions guide), so a recipient
  5422. # who has never written to the bot has no room to post into — say so
  5423. # instead of guessing at a server rejection later.
  5424. dm_room = await _find_dm_room(client, (await client.me()).id, target_user_id)
  5425. if dm_room is None:
  5426. raise _refuse(
  5427. f"No DM with {user_login or user_id} exists yet: on Chatto only a "
  5428. "person can start a DM, so they have to send the bot a message "
  5429. "once before it can message them"
  5430. )
  5431. message_ids, _root_id = await _post_chunks(client, dm_room.id, message)
  5432. return json.dumps(
  5433. {
  5434. "success": True,
  5435. "dm_room_id": dm_room.id,
  5436. "recipient": target_login,
  5437. "recipient_user_id": target_user_id,
  5438. "message_ids": message_ids,
  5439. "chunks_sent": len(message_ids),
  5440. }
  5441. )
  5442. async def _send_room(args: dict) -> str:
  5443. """Resolve the room, check the gates, post. See _handle_chatto_send_room."""
  5444. room_id = args.get("room_id") or ""
  5445. room_name = args.get("room_name") or ""
  5446. message = args.get("message") or ""
  5447. thread_root_event_id = args.get("thread_root_event_id") or ""
  5448. create_thread = bool(args.get("create_thread", False))
  5449. if not message:
  5450. raise _refuse("message is required")
  5451. if not room_id and not room_name:
  5452. raise _refuse("Exactly one of room_id or room_name is required")
  5453. if thread_root_event_id and create_thread:
  5454. raise _refuse("thread_root_event_id and create_thread are mutually exclusive")
  5455. cfg = _chatto_config_for_tools()
  5456. async with _tool_client(cfg) as client:
  5457. resolved = await _resolve_room(client, room_id, room_name)
  5458. room = resolved.room
  5459. # Posting into a room the plugin treats as read-only would break a
  5460. # promise the README makes about unlisted rooms staying silent.
  5461. if not _room_is_writable(cfg, room):
  5462. raise _read_only_room_refusal(room.name or room.id)
  5463. if create_thread and room.kind == RoomKind.DM:
  5464. raise _refuse(
  5465. "A DM has no threads: drop create_thread and send it as a normal message."
  5466. )
  5467. # The directory lists rooms the bot can see but has not joined, and
  5468. # posting into one fails server-side with an error that names neither
  5469. # the room nor the fix.
  5470. if not resolved.is_member:
  5471. raise _not_joined_refusal(room, "post there")
  5472. # A thread root has to belong to this room and has to BE a root, or
  5473. # the message attaches to a thread somewhere else entirely — or to
  5474. # none that can be followed. One shared check, so this tool and
  5475. # chatto_get_history cannot answer differently about the same ID.
  5476. if thread_root_event_id:
  5477. await _resolve_thread_root(client, room, thread_root_event_id)
  5478. message_ids, root_event_id = await _post_chunks(
  5479. client,
  5480. room.id,
  5481. message,
  5482. thread_root_event_id=thread_root_event_id,
  5483. create_thread=create_thread,
  5484. )
  5485. # Any thread the bot posts into is followed, not only one it opened:
  5486. # Chatto delivers a thread's replies to an account that follows it (or
  5487. # was mentioned in it directly), so replying into someone else's thread
  5488. # without following it can end the conversation the agent just joined.
  5489. # Mirrors the adapter's own send(), which follows every thread it uses.
  5490. if root_event_id:
  5491. try:
  5492. await client.follow_thread(room.id, root_event_id)
  5493. except Exception as exc:
  5494. # Follow is best-effort: the thread exists and the message was
  5495. # delivered, so a hiccup here is not a failed send.
  5496. logger.debug(
  5497. "Chatto tools: follow_thread(%s) failed: %s", root_event_id, exc
  5498. )
  5499. return json.dumps(
  5500. {
  5501. "success": True,
  5502. "room_id": room.id,
  5503. "room_name": room.name,
  5504. "message_ids": message_ids,
  5505. "chunks_sent": len(message_ids),
  5506. "thread_root_event_id": root_event_id,
  5507. "created_thread": bool(create_thread),
  5508. }
  5509. )
  5510. _EPHEMERAL_DELETION_TASKS: set[asyncio.Task[None]] = set()
  5511. async def _send_ephemeral(args: dict) -> str:
  5512. """Post a notice that deletes itself. See _handle_chatto_send_ephemeral."""
  5513. room_id = args.get("room_id") or ""
  5514. room_name = args.get("room_name") or ""
  5515. message = args.get("message") or ""
  5516. ttl_seconds = _int_arg(
  5517. args,
  5518. "ttl_seconds",
  5519. EPHEMERAL_TTL_DEFAULT,
  5520. low=EPHEMERAL_TTL_MIN,
  5521. high=EPHEMERAL_TTL_MAX,
  5522. )
  5523. if not message:
  5524. raise _refuse("message is required")
  5525. if not room_id and not room_name:
  5526. raise _refuse("Exactly one of room_id or room_name is required")
  5527. cfg = _chatto_config_for_tools()
  5528. if cfg is None:
  5529. raise _refuse("Chatto configuration unavailable")
  5530. async with _tool_client(cfg) as client:
  5531. resolved = await _resolve_room(client, room_id, room_name)
  5532. room = resolved.room
  5533. # Same gates as chatto_send_room: this tool posts, so it must not be a
  5534. # way into a room the plugin keeps read-only.
  5535. if not _room_is_writable(cfg, room):
  5536. raise _read_only_room_refusal(room.name or room.id)
  5537. if not resolved.is_member:
  5538. raise _not_joined_refusal(room, "post there")
  5539. message_ids, _root = await _post_chunks(client, room.id, message)
  5540. _schedule_ephemeral_deletion(cfg, room.id, message_ids, ttl_seconds)
  5541. return json.dumps(
  5542. {
  5543. "success": True,
  5544. "room_id": room.id,
  5545. "message_ids": message_ids,
  5546. "chunks_sent": len(message_ids),
  5547. "expires_in_seconds": ttl_seconds,
  5548. }
  5549. )
  5550. def _schedule_ephemeral_deletion(
  5551. cfg: ChattoConfiguration,
  5552. room_id: str,
  5553. event_ids: list[str],
  5554. ttl_seconds: int,
  5555. ) -> None:
  5556. """Delete a delivered notice once its TTL has passed, best-effort.
  5557. The task is held in a module-level set because asyncio keeps only a weak
  5558. reference: an unreferenced task can be collected before it ever runs.
  5559. Failure to delete is logged, never raised — the message was delivered, and
  5560. a process restart simply leaves it behind.
  5561. """
  5562. task = asyncio.create_task(_delete_after_ttl(cfg, room_id, event_ids, ttl_seconds))
  5563. _EPHEMERAL_DELETION_TASKS.add(task)
  5564. task.add_done_callback(_EPHEMERAL_DELETION_TASKS.discard)
  5565. async def _delete_after_ttl(
  5566. cfg: ChattoConfiguration,
  5567. room_id: str,
  5568. event_ids: list[str],
  5569. ttl_seconds: int,
  5570. ) -> None:
  5571. """Sleep out the TTL, then delete each chunk it covered."""
  5572. await asyncio.sleep(ttl_seconds)
  5573. try:
  5574. async with _tool_client(cfg) as client:
  5575. for event_id in event_ids:
  5576. try:
  5577. await client.delete_message(room_id, event_id)
  5578. except ChattoError as exc:
  5579. logger.debug(
  5580. "Chatto tools: ephemeral message %s in %s not deleted: %s",
  5581. event_id,
  5582. room_id,
  5583. exc,
  5584. )
  5585. except Exception as exc:
  5586. # No caller to raise to: the notice was delivered and this task exists
  5587. # only to make it disappear again. A transport oddity that chattolib
  5588. # did not map to ChattoError must not surface as an unretrieved task
  5589. # exception, so it is logged like any other cleanup failure.
  5590. logger.debug(
  5591. "Chatto tools: ephemeral cleanup of %s in %s failed: %s",
  5592. event_ids,
  5593. room_id,
  5594. exc,
  5595. exc_info=True,
  5596. )
  5597. async def _list_rooms(args: dict) -> str:
  5598. """List the rooms visible to the bot. See _handle_chatto_list_rooms."""
  5599. name_filter = (args.get("name") or "").strip().casefold()
  5600. async with _tool_client(_chatto_config_for_tools()) as client:
  5601. rooms_out = []
  5602. for rws in await client.list_rooms():
  5603. room = rws.room
  5604. if room is None:
  5605. continue
  5606. # A filter implies named rooms: skip DMs (empty name) and
  5607. # non-matching names alike.
  5608. if name_filter and not (room.name and name_filter in room.name.casefold()):
  5609. continue
  5610. rooms_out.append(
  5611. {
  5612. "room_id": room.id,
  5613. "name": room.name or "",
  5614. "kind": room.kind.value,
  5615. "threading_mode": room.threading_mode.value,
  5616. "archived": room.archived,
  5617. "is_member": rws.viewer_state.is_member,
  5618. # DM rooms carry no name, so they are labelled by their ID
  5619. # instead of leaving the model with a blank to match on.
  5620. "label": room.name or f"(DM room {room.id})",
  5621. }
  5622. )
  5623. return json.dumps(
  5624. {
  5625. "success": True,
  5626. "count": len(rooms_out),
  5627. "rooms": rooms_out,
  5628. "hint": (
  5629. "Use room_id in chatto_send_room, or as the chat_id part of a "
  5630. "cron deliver target like 'chatto-platform:<room_id>'."
  5631. ),
  5632. }
  5633. )
  5634. async def _list_room_attachments(args: dict) -> str:
  5635. """List file attachments in a Chatto room. See _handle_chatto_list_room_attachments."""
  5636. room_id = args.get("room_id") or ""
  5637. room_name = args.get("room_name") or ""
  5638. limit = _int_arg(
  5639. args, "limit", ATTACHMENT_PAGE_SIZE, low=1, high=ATTACHMENT_PAGE_SIZE * 5
  5640. )
  5641. offset = _int_arg(args, "offset", 0, low=0, high=100_000)
  5642. if not room_id and not room_name:
  5643. raise _refuse("Exactly one of room_id or room_name is required")
  5644. async with _tool_client(_chatto_config_for_tools()) as client:
  5645. resolved = await _resolve_room(client, room_id, room_name)
  5646. room = resolved.room
  5647. attachments, page = await client.list_room_attachments(
  5648. room.id, limit=limit, offset=offset
  5649. )
  5650. return json.dumps(
  5651. {
  5652. "success": True,
  5653. "room_id": room.id,
  5654. "room_name": room.name,
  5655. "count": len(attachments),
  5656. "offset": offset,
  5657. "has_more": page.has_more,
  5658. "total_count": page.total_count,
  5659. "attachments": attachments,
  5660. }
  5661. )
  5662. async def _list_pinned_messages(args: dict) -> str:
  5663. """List pinned messages in a Chatto room. See _handle_chatto_list_pinned_messages."""
  5664. room_id = args.get("room_id") or ""
  5665. room_name = args.get("room_name") or ""
  5666. limit = _int_arg(args, "limit", PINNED_PAGE_SIZE, low=1, high=PINNED_PAGE_SIZE * 5)
  5667. offset = _int_arg(args, "offset", 0, low=0, high=100_000)
  5668. if not room_id and not room_name:
  5669. raise _refuse("Exactly one of room_id or room_name is required")
  5670. async with _tool_client(_chatto_config_for_tools()) as client:
  5671. resolved = await _resolve_room(client, room_id, room_name)
  5672. room = resolved.room
  5673. page = await client.list_pinned_messages(room.id, limit=limit, offset=offset)
  5674. messages = [pm.message for pm in page.pinned_messages if pm.message is not None]
  5675. author_logins = await _batch_author_logins(
  5676. client, room.id, [msg.actor_id for msg in messages if msg.actor_id]
  5677. )
  5678. pinned_out = [
  5679. {
  5680. "event_id": msg.id,
  5681. "body": msg.body,
  5682. "author_id": msg.actor_id,
  5683. "author_login": author_logins.get(msg.actor_id) or "",
  5684. "posted_at": _iso_or_none(msg.created_at),
  5685. }
  5686. for msg in messages
  5687. ]
  5688. return json.dumps(
  5689. {
  5690. "success": True,
  5691. "room_id": room.id,
  5692. "room_name": room.name,
  5693. "count": len(pinned_out),
  5694. "has_more": page.page.has_more,
  5695. "total_count": page.page.total_count,
  5696. "pinned_messages": pinned_out,
  5697. "latest_pin_marker": page.latest_pin_marker,
  5698. }
  5699. )
  5700. async def _pin_message(args: dict) -> str:
  5701. """Pin or unpin a message in a Chatto room. See _handle_chatto_pin_message."""
  5702. room_id = args.get("room_id") or ""
  5703. room_name = args.get("room_name") or ""
  5704. event_id = args.get("event_id") or ""
  5705. pin = args.get("pin")
  5706. if not room_id and not room_name:
  5707. raise _refuse("Exactly one of room_id or room_name is required")
  5708. if not event_id:
  5709. raise _refuse("event_id is required")
  5710. if pin is None:
  5711. raise _refuse("pin (true/false) is required")
  5712. cfg = _chatto_config_for_tools()
  5713. async with _tool_client(cfg) as client:
  5714. resolved = await _resolve_room(client, room_id, room_name)
  5715. room = resolved.room
  5716. # Pinning changes what the room shows everyone, so it is a write:
  5717. # a room on neither mention list stays read-only, exactly as it does
  5718. # for chatto_send_room.
  5719. if not _room_is_writable(cfg, room):
  5720. raise _read_only_room_refusal(room.name or room.id)
  5721. if not resolved.is_member:
  5722. raise _not_joined_refusal(room, "pin a message there")
  5723. if pin:
  5724. await client.pin_message(room.id, event_id)
  5725. return json.dumps(
  5726. {
  5727. "success": True,
  5728. "action": "pinned",
  5729. "room_id": room.id,
  5730. "event_id": event_id,
  5731. }
  5732. )
  5733. unpinned = await client.unpin_message(room.id, event_id)
  5734. return json.dumps(
  5735. {
  5736. "success": True,
  5737. "action": "unpinned",
  5738. "room_id": room.id,
  5739. "event_id": event_id,
  5740. "unpinned": unpinned,
  5741. }
  5742. )
  5743. def _iso_or_none(moment: datetime | None) -> str | None:
  5744. """A Message timestamp as ISO-8601, or None when the server sent none.
  5745. chattolib's own formatter does the work: it pins a naive timestamp to UTC
  5746. instead of letting it print without an offset, so two timestamps from
  5747. different sources compare the way a reader expects.
  5748. """
  5749. if moment is None:
  5750. return None
  5751. return format_datetime(moment)
  5752. async def _batch_author_logins(
  5753. client: ChattoClient, room_id: str, actor_ids: list[str]
  5754. ) -> dict[str, str]:
  5755. """Map actor IDs to logins, using the room directory the bot may read.
  5756. ``batch_get_room_members`` needs no admin rights and answers member
  5757. profiles for the caller's own rooms, so it is the one sanctioned way to
  5758. turn an ``actor_id`` into a name here. Members who left (or were never
  5759. members) come back missing — their IDs stay as their only label, which
  5760. is still unambiguous for the caller. A directory that refuses the call
  5761. costs the names, not the messages: the logins are enrichment, and an
  5762. unreadable roster must not make a readable history unreadable.
  5763. """
  5764. unique_ids = list({actor_id for actor_id in actor_ids if actor_id})
  5765. if not unique_ids:
  5766. return {}
  5767. try:
  5768. members = await client.batch_get_room_members(room_id, unique_ids)
  5769. except ChattoError as exc:
  5770. logger.debug("Chatto tools: members of room %s unreadable: %s", room_id, exc)
  5771. return {}
  5772. logins: dict[str, str] = {}
  5773. for member in members:
  5774. if member.user is not None and member.user.id:
  5775. logins[member.user.id] = member.user.login
  5776. return logins
  5777. def _attachment_out(attachment: MessageAttachment) -> dict[str, Any]:
  5778. """One attachment as the tool's JSON shape."""
  5779. out: dict[str, Any] = {
  5780. "id": attachment.id,
  5781. "filename": attachment.filename,
  5782. "content_type": attachment.content_type,
  5783. "width": attachment.width,
  5784. "height": attachment.height,
  5785. "description": attachment.description,
  5786. }
  5787. if attachment.asset_url is not None:
  5788. out["asset_url"] = attachment.asset_url.url
  5789. if attachment.thumbnail_asset_url is not None:
  5790. out["thumbnail_asset_url"] = attachment.thumbnail_asset_url.url
  5791. if attachment.video_processing is not None:
  5792. # A video carries its own dimensions, duration and transcoded
  5793. # variants, and its own URL only once the server has produced one —
  5794. # without this block the tool reports a video as an attachment with no
  5795. # size, no length and nothing to fetch.
  5796. video = attachment.video_processing
  5797. out["video"] = {
  5798. "duration_ms": video.duration_ms,
  5799. "status": video.status.name,
  5800. "thumbnail_url": (
  5801. video.thumbnail_asset_url.url
  5802. if video.thumbnail_asset_url is not None
  5803. else None
  5804. ),
  5805. "variants": [
  5806. {
  5807. "quality": variant.quality,
  5808. "width": variant.width,
  5809. "height": variant.height,
  5810. "size": variant.size,
  5811. "url": (
  5812. variant.asset_url.url if variant.asset_url is not None else None
  5813. ),
  5814. }
  5815. for variant in video.variants
  5816. ],
  5817. }
  5818. return out
  5819. def _message_out(message: Message, author_logins: dict[str, str]) -> dict[str, Any]:
  5820. """A Message as the tool's JSON shape — every field the caller can act on."""
  5821. return {
  5822. "event_id": message.id,
  5823. "room_id": message.room_id,
  5824. "author_user_id": message.actor_id,
  5825. "author_login": author_logins.get(message.actor_id),
  5826. "created_at": _iso_or_none(message.created_at),
  5827. "updated_at": _iso_or_none(message.updated_at),
  5828. "deleted_at": _iso_or_none(message.deleted_at),
  5829. "body": message.body,
  5830. "in_reply_to": message.in_reply_to or None,
  5831. "thread_root_event_id": message.thread_root_event_id or None,
  5832. "pinned": message.pinned,
  5833. "attachments": [
  5834. _attachment_out(attachment) for attachment in message.attachments
  5835. ],
  5836. "reactions": [
  5837. {
  5838. "emoji": reaction.emoji,
  5839. "count": reaction.count,
  5840. "has_reacted": reaction.has_reacted,
  5841. }
  5842. for reaction in message.reactions
  5843. ],
  5844. "link_preview": (
  5845. {"url": message.link_preview.url, "title": message.link_preview.title}
  5846. if message.link_preview is not None
  5847. else None
  5848. ),
  5849. "thread_summary": (
  5850. {
  5851. "thread_root_event_id": message.thread.thread_root_event_id,
  5852. "reply_count": message.thread.reply_count,
  5853. "participant_count": message.thread.participant_count,
  5854. }
  5855. if message.thread is not None
  5856. else None
  5857. ),
  5858. }
  5859. async def _get_message(args: dict) -> str:
  5860. """Resolve the room, fetch the message(s). See _handle_chatto_get_message."""
  5861. room_id = args.get("room_id") or ""
  5862. room_name = args.get("room_name") or ""
  5863. event_id = args.get("event_id") or ""
  5864. event_ids = [e for e in (args.get("event_ids") or []) if e]
  5865. follow_reply_chain = _int_arg(
  5866. args, "follow_reply_chain", 0, low=0, high=FOLLOW_REPLY_CHAIN_MAX
  5867. )
  5868. if not room_id and not room_name:
  5869. raise _refuse("Exactly one of room_id or room_name is required")
  5870. if not event_id and not event_ids:
  5871. raise _refuse("Exactly one of event_id or event_ids is required")
  5872. if event_id and event_ids:
  5873. raise _refuse("event_id and event_ids are mutually exclusive")
  5874. if event_ids and follow_reply_chain:
  5875. # A chain belongs to one message. With several requested there is no
  5876. # single answer, and picking one would hand back a conversation the
  5877. # caller did not ask for.
  5878. raise _refuse(
  5879. "follow_reply_chain applies to a single event_id — read one message "
  5880. "per call to follow its chain"
  5881. )
  5882. async with _tool_client(_chatto_config_for_tools()) as client:
  5883. resolved = await _resolve_room(client, room_id, room_name)
  5884. room = resolved.room
  5885. # Every read RPC the plugin uses documents room membership as a
  5886. # precondition (GetRoomEvents, GetMessage, BatchGetMessages), so an
  5887. # unjoined room is unreadable whatever the mention lists say. Saying so
  5888. # here beats a PERMISSION_DENIED that names neither the room nor the fix.
  5889. if not resolved.is_member:
  5890. raise _not_joined_refusal(room, "read it there")
  5891. if event_id:
  5892. # One message is one lookup: the single-message RPC is the
  5893. # authoritative one, so there is no batch to fall back from.
  5894. single = await client.get_message(room.id, event_id)
  5895. found = {single.id: single} if single is not None else {}
  5896. missing = [] if single is not None else [event_id]
  5897. else:
  5898. fetched = await client.batch_get_messages(room.id, event_ids)
  5899. by_id = {m.id: m for m in fetched if m.id}
  5900. # Reported in the order they were asked for, not the order the
  5901. # server happened to answer in.
  5902. found = {eid: by_id[eid] for eid in event_ids if eid in by_id}
  5903. missing = [eid for eid in event_ids if eid not in found]
  5904. if not found:
  5905. raise _refuse(
  5906. f"No message {', '.join(missing)} found in room {room.id}. "
  5907. "Check the event ID and the room."
  5908. )
  5909. # The reply chain walks in_reply_to backwards, oldest ancestor first,
  5910. # one hop per call — a chain is a path, so it cannot be batched. A hop
  5911. # the server cannot resolve ends the chain: the ancestors above it are
  5912. # unreachable, and stopping beats reporting a hole as the top.
  5913. chain: list[Message] = []
  5914. if follow_reply_chain > 0:
  5915. frontier_id = next(iter(found.values())).in_reply_to
  5916. hops = follow_reply_chain
  5917. while frontier_id and hops > 0:
  5918. ancestor = await client.get_message(room.id, frontier_id)
  5919. if ancestor is None:
  5920. break
  5921. chain.append(ancestor)
  5922. frontier_id = ancestor.in_reply_to
  5923. hops -= 1
  5924. chain.reverse()
  5925. author_ids = [m.actor_id for m in found.values()] + [m.actor_id for m in chain]
  5926. author_logins = await _batch_author_logins(client, room.id, author_ids)
  5927. return json.dumps(
  5928. {
  5929. "success": True,
  5930. "room_id": room.id,
  5931. "room_name": room.name,
  5932. "messages": [_message_out(m, author_logins) for m in found.values()],
  5933. "missing_event_ids": missing,
  5934. "reply_chain": [_message_out(m, author_logins) for m in chain],
  5935. }
  5936. )
  5937. async def _get_history(args: dict) -> str:
  5938. """Resolve the room, read the timeline. See _handle_chatto_get_history."""
  5939. room_id = args.get("room_id") or ""
  5940. room_name = args.get("room_name") or ""
  5941. thread_root_event_id = args.get("thread_root_event_id") or ""
  5942. limit = _int_arg(args, "limit", HISTORY_PAGE_SIZE, low=1, high=HISTORY_PAGE_MAX)
  5943. before = args.get("before") or ""
  5944. after = args.get("after") or ""
  5945. if not room_id and not room_name:
  5946. raise _refuse("Exactly one of room_id or room_name is required")
  5947. if before and after:
  5948. # The client sends `before` OR `after` and drops the second without a
  5949. # word, so both would answer a question nobody asked.
  5950. raise _refuse(
  5951. "before and after are mutually exclusive — pick the direction you "
  5952. "want to page in"
  5953. )
  5954. async with _tool_client(_chatto_config_for_tools()) as client:
  5955. resolved = await _resolve_room(client, room_id, room_name)
  5956. room = resolved.room
  5957. # A read of an unjoined room fails server-side whatever the mention
  5958. # lists say; saying so here names the room and the way in.
  5959. if not resolved.is_member:
  5960. raise _not_joined_refusal(room, "read its history there")
  5961. root: Message | None = None
  5962. if thread_root_event_id:
  5963. root = await _resolve_thread_root(client, room, thread_root_event_id)
  5964. page = await client.get_thread_events(
  5965. room.id,
  5966. thread_root_event_id,
  5967. limit=limit,
  5968. before=before or None,
  5969. after=after or None,
  5970. )
  5971. else:
  5972. page = await client.get_room_events(
  5973. room.id, limit=limit, before=before or None, after=after or None
  5974. )
  5975. messages = [ev.message for ev in page.events if ev.message is not None]
  5976. if root is not None and all(m.id != root.id for m in messages):
  5977. # Whether the server lists the root back as the thread's first
  5978. # event is not something the client signature promises, and a
  5979. # thread read without its root is a conversation whose opening
  5980. # line is missing. The root is already in hand, so putting it back
  5981. # costs nothing.
  5982. messages.insert(0, root)
  5983. messages = _oldest_first(messages)
  5984. # The timeline page carries its own user directory (``users_by_id``),
  5985. # which answers author names without a member-list call. Fall back to
  5986. # the room directory for actors the page did not include.
  5987. author_logins = {
  5988. user_id: user.login
  5989. for user_id, user in page.users_by_id.items()
  5990. if user.login
  5991. }
  5992. unresolved = [
  5993. m.actor_id
  5994. for m in messages
  5995. if m.actor_id and m.actor_id not in author_logins
  5996. ]
  5997. if unresolved:
  5998. author_logins.update(
  5999. await _batch_author_logins(client, room.id, unresolved)
  6000. )
  6001. return json.dumps(
  6002. {
  6003. "success": True,
  6004. "room_id": room.id,
  6005. "room_name": room.name,
  6006. "thread_root_event_id": thread_root_event_id or None,
  6007. "count": len(messages),
  6008. "has_older": page.has_older,
  6009. "has_newer": page.has_newer,
  6010. # Paging is the caller's next call, so this answer has to carry
  6011. # the positions that next call takes as its arguments —
  6012. # otherwise the model would have to guess which message to
  6013. # anchor on.
  6014. "start_cursor": page.start_cursor,
  6015. "end_cursor": page.end_cursor,
  6016. "messages": [_message_out(m, author_logins) for m in messages],
  6017. }
  6018. )
  6019. def _search_result_out(
  6020. result: MessageSearchResult, author_logins: dict[str, str]
  6021. ) -> dict[str, Any]:
  6022. """One search hit as the tool's JSON shape.
  6023. A hit is a pointer, not a record: ``chatto_get_message`` is what reads one
  6024. in full, so this carries what decides *which* hit to read — where it is,
  6025. who said it, when, what it says — and leaves the reaction and attachment
  6026. detail to that call.
  6027. """
  6028. message = result.message
  6029. out: dict[str, Any] = {"relevance": round(result.relevance_score, 4)}
  6030. if message is not None:
  6031. out.update(
  6032. {
  6033. "event_id": message.id,
  6034. "room_id": message.room_id,
  6035. "author_user_id": message.actor_id,
  6036. "author_login": author_logins.get(message.actor_id),
  6037. "created_at": _iso_or_none(message.created_at),
  6038. "body": message.body,
  6039. "in_reply_to": message.in_reply_to or None,
  6040. "thread_root_event_id": message.thread_root_event_id or None,
  6041. }
  6042. )
  6043. context = result.thread_context
  6044. if context is not None:
  6045. # Only THREAD grouping asks for this: the row stands for a whole
  6046. # conversation, so the caller needs its opening line and how far it got,
  6047. # not just the message the provider matched.
  6048. root = context.root_message
  6049. latest = context.latest_reply
  6050. thread = context.thread
  6051. out["thread"] = {
  6052. "root_event_id": (
  6053. thread.thread_root_event_id
  6054. if thread is not None
  6055. else (root.id if root is not None else None)
  6056. ),
  6057. "root_body": root.body if root is not None else None,
  6058. "room_id": context.room.id if context.room is not None else None,
  6059. "room_name": context.room.name if context.room is not None else None,
  6060. "reply_count": thread.reply_count if thread is not None else None,
  6061. "participant_count": (
  6062. thread.participant_count if thread is not None else None
  6063. ),
  6064. "last_reply_at": (
  6065. _iso_or_none(thread.last_reply_at) if thread is not None else None
  6066. ),
  6067. "latest_reply_event_id": latest.id if latest is not None else None,
  6068. "latest_reply_body": latest.body if latest is not None else None,
  6069. }
  6070. return out
  6071. async def _search_unavailable_reason(
  6072. client: ChattoClient, exc: ChattoConnectError
  6073. ) -> str:
  6074. """Why search cannot answer, in terms the caller can act on.
  6075. The server reports one of two codes for two very different situations:
  6076. the operator turned search off, or the provider is not ready yet. The first
  6077. never resolves on its own, the second does — saying which one it is changes
  6078. what the caller should do next. ``GetStatus`` stays available while search
  6079. is disabled, so it is the one call that can tell them apart.
  6080. """
  6081. try:
  6082. status = await client.get_search_status()
  6083. except ChattoError as status_exc:
  6084. logger.debug("Chatto tools: search status unreadable: %s", status_exc)
  6085. return f"Message search is unavailable on this Chatto server ({exc.code})"
  6086. hint = _SEARCH_STATE_HINTS.get(status.state)
  6087. if hint is None:
  6088. return f"Message search is unavailable on this Chatto server ({exc.code})"
  6089. reason = f"Message search is unavailable: {hint}"
  6090. if status.retry_after_seconds:
  6091. reason += f" (retry in about {status.retry_after_seconds}s)"
  6092. return reason
  6093. async def _search_messages(args: dict) -> str:
  6094. """Search message bodies. See _handle_chatto_search_messages."""
  6095. query = str(args.get("query") or "").strip()
  6096. room_id = args.get("room_id") or ""
  6097. room_name = args.get("room_name") or ""
  6098. author_id = args.get("author_id") or ""
  6099. cursor = args.get("cursor") or ""
  6100. limit = _int_arg(args, "limit", SEARCH_PAGE_SIZE, low=1, high=SEARCH_PAGE_MAX)
  6101. created_after = _timestamp_arg(args, "created_after")
  6102. created_before = _timestamp_arg(args, "created_before")
  6103. order = _enum_arg(args, "order", _SEARCH_ORDERS, MessageSearchOrder.RELEVANCE)
  6104. group_by = _enum_arg(
  6105. args, "group_by", _SEARCH_GROUPS, MessageSearchGroupBy.UNSPECIFIED
  6106. )
  6107. scope = _enum_arg(args, "scope", _SEARCH_SCOPES, MessageSearchScope.UNSPECIFIED)
  6108. has_attachments = args.get("has_attachments")
  6109. if not query:
  6110. raise _refuse("query is required and must not be empty")
  6111. if room_id and room_name:
  6112. raise _refuse("room_id and room_name are mutually exclusive")
  6113. if has_attachments is not None and not isinstance(has_attachments, bool):
  6114. raise _refuse("has_attachments must be true or false")
  6115. if order is MessageSearchOrder.THREAD_ACTIVITY and (
  6116. group_by is not MessageSearchGroupBy.THREAD
  6117. ):
  6118. # The server refuses this combination; saying which two arguments
  6119. # collide is more useful than relaying INVALID_ARGUMENT.
  6120. raise _refuse("order 'thread_activity' requires group_by 'thread'")
  6121. if created_after and created_before and created_after >= created_before:
  6122. raise _refuse("created_after must be earlier than created_before")
  6123. async with _tool_client(_chatto_config_for_tools()) as client:
  6124. if room_id or room_name:
  6125. room_id = (await _resolve_room(client, room_id, room_name)).room.id
  6126. try:
  6127. page = await client.search_messages(
  6128. query,
  6129. room_id=room_id or None,
  6130. author_id=author_id or None,
  6131. created_after=created_after,
  6132. created_before=created_before,
  6133. has_attachments=has_attachments,
  6134. order=order,
  6135. page_size=limit,
  6136. cursor=cursor or None,
  6137. scope=scope,
  6138. group_by=group_by,
  6139. )
  6140. except ChattoConnectError as exc:
  6141. if exc.code not in {"failed_precondition", "unavailable"}:
  6142. raise
  6143. raise _refuse(await _search_unavailable_reason(client, exc)) from exc
  6144. results = page.results
  6145. # The page carries its own user directory, which answers author names
  6146. # without a member-list call. A cross-room search can still miss an
  6147. # author, so the remaining ones are resolved per room — the directory
  6148. # call is per room, and a hit names the room it came from.
  6149. author_logins = {
  6150. user_id: user.login
  6151. for user_id, user in page.users_by_id.items()
  6152. if user.login
  6153. }
  6154. unresolved_by_room: dict[str, list[str]] = {}
  6155. for result in results:
  6156. message = result.message
  6157. if message is None or not message.actor_id:
  6158. continue
  6159. if message.actor_id in author_logins:
  6160. continue
  6161. unresolved_by_room.setdefault(message.room_id, []).append(message.actor_id)
  6162. for hit_room_id, actor_ids in unresolved_by_room.items():
  6163. if hit_room_id:
  6164. author_logins.update(
  6165. await _batch_author_logins(client, hit_room_id, actor_ids)
  6166. )
  6167. return json.dumps(
  6168. {
  6169. "success": True,
  6170. "query": query,
  6171. "room_id": room_id or None,
  6172. "count": len(results),
  6173. "grouped_by_thread": group_by is MessageSearchGroupBy.THREAD,
  6174. "thread_total_count": page.thread_total_count,
  6175. "next_cursor": page.next_cursor or None,
  6176. "results": [
  6177. _search_result_out(result, author_logins) for result in results
  6178. ],
  6179. }
  6180. )
  6181. async def _handle_chatto_search_messages(args: dict) -> str:
  6182. """Tool handler for chatto_search_messages.
  6183. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6184. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6185. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6186. refusal's own JSON, so no path escapes as an unhandled error.
  6187. """
  6188. try:
  6189. return await _search_messages(args)
  6190. except _ToolRefusal as refusal:
  6191. return refusal.result_json
  6192. except ChattoAuthError as exc:
  6193. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6194. except ChattoError as exc:
  6195. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6196. async def _handle_chatto_send_dm(args: dict) -> str:
  6197. """Tool handler for chatto_send_dm.
  6198. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6199. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6200. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6201. refusal's own JSON, so no path escapes as an unhandled error.
  6202. """
  6203. try:
  6204. return await _send_dm(args)
  6205. except _ToolRefusal as refusal:
  6206. return refusal.result_json
  6207. except ChattoAuthError as exc:
  6208. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6209. except ChattoError as exc:
  6210. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6211. async def _handle_chatto_send_room(args: dict) -> str:
  6212. """Tool handler for chatto_send_room.
  6213. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6214. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6215. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6216. refusal's own JSON, so no path escapes as an unhandled error.
  6217. """
  6218. try:
  6219. return await _send_room(args)
  6220. except _ToolRefusal as refusal:
  6221. return refusal.result_json
  6222. except ChattoAuthError as exc:
  6223. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6224. except ChattoError as exc:
  6225. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6226. async def _handle_chatto_send_ephemeral(args: dict) -> str:
  6227. """Tool handler for chatto_send_ephemeral.
  6228. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6229. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6230. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6231. refusal's own JSON, so no path escapes as an unhandled error.
  6232. """
  6233. try:
  6234. return await _send_ephemeral(args)
  6235. except _ToolRefusal as refusal:
  6236. return refusal.result_json
  6237. except ChattoAuthError as exc:
  6238. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6239. except ChattoError as exc:
  6240. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6241. async def _handle_chatto_list_rooms(args: dict) -> str:
  6242. """Tool handler for chatto_list_rooms.
  6243. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6244. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6245. type".
  6246. """
  6247. try:
  6248. return await _list_rooms(args)
  6249. except _ToolRefusal as refusal:
  6250. return refusal.result_json
  6251. except ChattoAuthError as exc:
  6252. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6253. except ChattoError as exc:
  6254. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6255. async def _handle_chatto_set_custom_status(args: dict) -> str:
  6256. """Tool handler for chatto_set_custom_status.
  6257. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6258. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6259. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6260. refusal's own JSON, so no path escapes as an unhandled error.
  6261. """
  6262. try:
  6263. return await _set_custom_status(args)
  6264. except _ToolRefusal as refusal:
  6265. return refusal.result_json
  6266. except ChattoAuthError as exc:
  6267. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6268. except ChattoError as exc:
  6269. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6270. async def _handle_chatto_delete_custom_status(args: dict) -> str:
  6271. """Tool handler for chatto_delete_custom_status.
  6272. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6273. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6274. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6275. refusal's own JSON, so no path escapes as an unhandled error.
  6276. """
  6277. try:
  6278. return await _delete_custom_status(args)
  6279. except _ToolRefusal as refusal:
  6280. return refusal.result_json
  6281. except ChattoAuthError as exc:
  6282. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6283. except ChattoError as exc:
  6284. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6285. async def _set_custom_status(args: dict) -> str:
  6286. """Set the bot's custom status. See _handle_chatto_set_custom_status."""
  6287. emoji = (args.get("emoji") or "").strip()
  6288. text = (args.get("text") or "").strip()
  6289. expires_in = args.get("expires_in_seconds")
  6290. if expires_in is not None:
  6291. expires_in = int(expires_in)
  6292. if expires_in < 0:
  6293. raise _refuse("expires_in_seconds must be non-negative")
  6294. if not emoji or not text:
  6295. raise _refuse("emoji and text are required")
  6296. async with _tool_client(_chatto_config_for_tools()) as client:
  6297. expires_at = None
  6298. if expires_in and expires_in > 0:
  6299. from datetime import UTC, datetime, timedelta
  6300. expires_at = datetime.now(UTC) + timedelta(seconds=expires_in)
  6301. await client.set_custom_status(emoji, text, expires_at=expires_at)
  6302. return json.dumps(
  6303. {
  6304. "success": True,
  6305. "emoji": emoji,
  6306. "text": text,
  6307. "expires_at": (_iso_or_none(expires_at) if expires_at else None),
  6308. }
  6309. )
  6310. async def _delete_custom_status(args: dict) -> str:
  6311. """Clear the bot's custom status. See _handle_chatto_delete_custom_status."""
  6312. async with _tool_client(_chatto_config_for_tools()) as client:
  6313. await client.delete_custom_status()
  6314. return json.dumps({"success": True, "message": "Custom status cleared"})
  6315. async def _fetch_link_preview(args: dict) -> str:
  6316. """Fetch an OpenGraph link preview. See _handle_chatto_fetch_link_preview."""
  6317. url = (args.get("url") or "").strip()
  6318. if not url:
  6319. raise _refuse("url is required")
  6320. async with _tool_client(_chatto_config_for_tools()) as client:
  6321. preview, _ = await client.fetch_link_preview(url)
  6322. return json.dumps(
  6323. {
  6324. "success": True,
  6325. "url": url,
  6326. "title": preview.title if preview else None,
  6327. "description": preview.description if preview else None,
  6328. "image_url": preview.image_url if preview else None,
  6329. "site_name": preview.site_name if preview else None,
  6330. "embed_type": preview.embed_type if preview else None,
  6331. }
  6332. )
  6333. async def _mark_thread_as_read(args: dict) -> str:
  6334. """Mark a thread as read. See _handle_chatto_mark_thread_as_read."""
  6335. room_id = args.get("room_id") or ""
  6336. room_name = args.get("room_name") or ""
  6337. thread_root_event_id = args.get("thread_root_event_id") or ""
  6338. if not room_id and not room_name:
  6339. raise _refuse("Exactly one of room_id or room_name is required")
  6340. if not thread_root_event_id:
  6341. raise _refuse("thread_root_event_id is required")
  6342. async with _tool_client(_chatto_config_for_tools()) as client:
  6343. if not room_id:
  6344. resolved = await _resolve_room(client, room_id, room_name)
  6345. room_id = resolved.room.id
  6346. prev_last_read = await client.mark_thread_as_read(room_id, thread_root_event_id)
  6347. return json.dumps(
  6348. {
  6349. "success": True,
  6350. "room_id": room_id,
  6351. "thread_root_event_id": thread_root_event_id,
  6352. "previous_last_read_at": (
  6353. _iso_or_none(prev_last_read) if prev_last_read else None
  6354. ),
  6355. }
  6356. )
  6357. async def _list_room_groups(args: dict) -> str:
  6358. """List room groups. See _handle_chatto_list_room_groups."""
  6359. async with _tool_client(_chatto_config_for_tools()) as client:
  6360. groups = await client.list_room_groups()
  6361. results: list[dict] = []
  6362. for g in groups:
  6363. results.append(
  6364. {
  6365. "id": g.id,
  6366. "name": g.name,
  6367. "description": g.description or "",
  6368. "room_count": len(g.rooms),
  6369. "room_ids": [rws.room.id for rws in g.rooms if rws.room],
  6370. "sidebar_links": [
  6371. {"id": l.id, "label": l.label, "url": l.url}
  6372. for l in g.sidebar_links
  6373. ],
  6374. }
  6375. )
  6376. return json.dumps({"success": True, "groups": results})
  6377. async def _handle_chatto_fetch_link_preview(args: dict) -> str:
  6378. """Tool handler for chatto_fetch_link_preview.
  6379. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6380. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6381. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6382. refusal's own JSON, so no path escapes as an unhandled error.
  6383. """
  6384. try:
  6385. return await _fetch_link_preview(args)
  6386. except _ToolRefusal as refusal:
  6387. return refusal.result_json
  6388. except ChattoAuthError as exc:
  6389. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6390. except ChattoError as exc:
  6391. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6392. async def _handle_chatto_mark_thread_as_read(args: dict) -> str:
  6393. """Tool handler for chatto_mark_thread_as_read.
  6394. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6395. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6396. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6397. refusal's own JSON, so no path escapes as an unhandled error.
  6398. """
  6399. try:
  6400. return await _mark_thread_as_read(args)
  6401. except _ToolRefusal as refusal:
  6402. return refusal.result_json
  6403. except ChattoAuthError as exc:
  6404. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6405. except ChattoError as exc:
  6406. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6407. async def _handle_chatto_get_message(args: dict) -> str:
  6408. """Tool handler for chatto_get_message.
  6409. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6410. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6411. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6412. refusal's own JSON, so no path escapes as an unhandled error.
  6413. """
  6414. try:
  6415. return await _get_message(args)
  6416. except _ToolRefusal as refusal:
  6417. return refusal.result_json
  6418. except ChattoAuthError as exc:
  6419. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6420. except ChattoError as exc:
  6421. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6422. async def _handle_chatto_get_history(args: dict) -> str:
  6423. """Tool handler for chatto_get_history.
  6424. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6425. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6426. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6427. refusal's own JSON, so no path escapes as an unhandled error.
  6428. """
  6429. try:
  6430. return await _get_history(args)
  6431. except _ToolRefusal as refusal:
  6432. return refusal.result_json
  6433. except ChattoAuthError as exc:
  6434. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6435. except ChattoError as exc:
  6436. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6437. async def _handle_chatto_list_room_groups(args: dict) -> str:
  6438. """Tool handler for chatto_list_room_groups.
  6439. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6440. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6441. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6442. refusal's own JSON, so no path escapes as an unhandled error.
  6443. """
  6444. try:
  6445. return await _list_room_groups(args)
  6446. except _ToolRefusal as refusal:
  6447. return refusal.result_json
  6448. except ChattoAuthError as exc:
  6449. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6450. except ChattoError as exc:
  6451. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6452. async def _handle_chatto_list_room_attachments(args: dict) -> str:
  6453. """Tool handler for chatto_list_room_attachments.
  6454. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6455. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6456. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6457. refusal's own JSON, so no path escapes as an unhandled error.
  6458. """
  6459. try:
  6460. return await _list_room_attachments(args)
  6461. except _ToolRefusal as refusal:
  6462. return refusal.result_json
  6463. except ChattoAuthError as exc:
  6464. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6465. except ChattoError as exc:
  6466. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6467. async def _handle_chatto_list_pinned_messages(args: dict) -> str:
  6468. """Tool handler for chatto_list_pinned_messages.
  6469. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6470. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6471. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6472. refusal's own JSON, so no path escapes as an unhandled error.
  6473. """
  6474. try:
  6475. return await _list_pinned_messages(args)
  6476. except _ToolRefusal as refusal:
  6477. return refusal.result_json
  6478. except ChattoAuthError as exc:
  6479. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6480. except ChattoError as exc:
  6481. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6482. async def _handle_chatto_pin_message(args: dict) -> str:
  6483. """Tool handler for chatto_pin_message.
  6484. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  6485. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  6486. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  6487. refusal's own JSON, so no path escapes as an unhandled error.
  6488. """
  6489. try:
  6490. return await _pin_message(args)
  6491. except _ToolRefusal as refusal:
  6492. return refusal.result_json
  6493. except ChattoAuthError as exc:
  6494. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  6495. except ChattoError as exc:
  6496. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  6497. def _register_bundled_skills(ctx) -> None:
  6498. """Register the skills shipped in ``skills/``, each with its own description.
  6499. ``register_skill`` stores the description verbatim and never reads the
  6500. SKILL.md frontmatter, so passing none leaves the skill listed in
  6501. ``<available_skills>`` with nothing explaining when to load it — which is
  6502. the only place an agent learns it exists.
  6503. """
  6504. from pathlib import Path
  6505. from agent.skill_utils import parse_frontmatter
  6506. skills_dir = Path(__file__).parent / "skills"
  6507. if not skills_dir.is_dir():
  6508. logger.debug("Chatto: no bundled skills directory at %s", skills_dir)
  6509. return
  6510. for child in sorted(skills_dir.iterdir()):
  6511. skill_md = child / "SKILL.md"
  6512. if not (child.is_dir() and skill_md.exists()):
  6513. continue
  6514. frontmatter, _ = parse_frontmatter(skill_md.read_text(encoding="utf-8"))
  6515. ctx.register_skill(
  6516. child.name,
  6517. str(skill_md),
  6518. description=str(frontmatter.get("description") or ""),
  6519. frontmatter=frontmatter,
  6520. )
  6521. logger.info("Chatto plugin skill registered: %s", child.name)
  6522. # The plugin's outbound tools: (tool name, JSON schema, handler). One list, so
  6523. # the two registration entry points below cannot disagree about what exists.
  6524. _PLUGIN_TOOLS = (
  6525. ("chatto_send_dm", CHATTO_SEND_DM_SCHEMA, _handle_chatto_send_dm),
  6526. ("chatto_send_room", CHATTO_SEND_ROOM_SCHEMA, _handle_chatto_send_room),
  6527. (
  6528. "chatto_send_ephemeral",
  6529. CHATTO_SEND_EPHEMERAL_SCHEMA,
  6530. _handle_chatto_send_ephemeral,
  6531. ),
  6532. ("chatto_list_rooms", CHATTO_LIST_ROOMS_SCHEMA, _handle_chatto_list_rooms),
  6533. ("chatto_get_message", CHATTO_GET_MESSAGE_SCHEMA, _handle_chatto_get_message),
  6534. ("chatto_get_history", CHATTO_GET_HISTORY_SCHEMA, _handle_chatto_get_history),
  6535. (
  6536. "chatto_search_messages",
  6537. CHATTO_SEARCH_MESSAGES_SCHEMA,
  6538. _handle_chatto_search_messages,
  6539. ),
  6540. (
  6541. "chatto_list_room_attachments",
  6542. CHATTO_LIST_ROOM_ATTACHMENTS_SCHEMA,
  6543. _handle_chatto_list_room_attachments,
  6544. ),
  6545. (
  6546. "chatto_list_pinned_messages",
  6547. CHATTO_LIST_PINNED_MESSAGES_SCHEMA,
  6548. _handle_chatto_list_pinned_messages,
  6549. ),
  6550. (
  6551. "chatto_pin_message",
  6552. CHATTO_PIN_MESSAGE_SCHEMA,
  6553. _handle_chatto_pin_message,
  6554. ),
  6555. (
  6556. "chatto_set_custom_status",
  6557. CHATTO_SET_CUSTOM_STATUS_SCHEMA,
  6558. _handle_chatto_set_custom_status,
  6559. ),
  6560. (
  6561. "chatto_delete_custom_status",
  6562. CHATTO_DELETE_CUSTOM_STATUS_SCHEMA,
  6563. _handle_chatto_delete_custom_status,
  6564. ),
  6565. (
  6566. "chatto_fetch_link_preview",
  6567. CHATTO_FETCH_LINK_PREVIEW_SCHEMA,
  6568. _handle_chatto_fetch_link_preview,
  6569. ),
  6570. (
  6571. "chatto_mark_thread_as_read",
  6572. CHATTO_MARK_THREAD_AS_READ_SCHEMA,
  6573. _handle_chatto_mark_thread_as_read,
  6574. ),
  6575. (
  6576. "chatto_list_room_groups",
  6577. CHATTO_LIST_ROOM_GROUPS_SCHEMA,
  6578. _handle_chatto_list_room_groups,
  6579. ),
  6580. )
  6581. def register_plugin_tools(ctx) -> None:
  6582. """Register the plugin's outbound tools in the ``chatto-platform`` toolset.
  6583. Reached through two doors: ``register()`` in a gateway/web process, which
  6584. materializes the platform, and ``tools.register_tools`` in a CLI/TUI one,
  6585. which never does. A tool list written out twice would mean tools that exist
  6586. in only half the sessions, so both doors call this.
  6587. """
  6588. for name, schema, handler in _PLUGIN_TOOLS:
  6589. ctx.register_tool(
  6590. name=name,
  6591. toolset="chatto-platform",
  6592. schema=schema,
  6593. handler=handler,
  6594. is_async=True,
  6595. description=schema["description"],
  6596. )
  6597. def register(ctx) -> None:
  6598. """Plugin entry point — called by the Hermes plugin system."""
  6599. logger.info("Registering Chatto platform plugin on Hermes Agent")
  6600. # --- Plugin tools ---
  6601. register_plugin_tools(ctx)
  6602. # --- Bundled skills ---
  6603. # Ship the plugin's own usage/development knowledge with the code, so any
  6604. # agent using this plugin knows when/how to use its tools and how to
  6605. # extend it. Loaded via skill_view("chatto-platform:chatto-platform-plugin").
  6606. _register_bundled_skills(ctx)
  6607. for capability in _capabilities():
  6608. logger.info("Chatto capability: %s", capability)
  6609. ctx.register_platform(
  6610. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  6611. label=ChattoConstants.PLATFORM_LABEL,
  6612. adapter_factory=hermes_adapter_factory,
  6613. check_fn=hermes_check_fn,
  6614. validate_config=hermes_validate_config,
  6615. is_connected=hermes_is_connected,
  6616. install_hint=ChattoConstants.INSTALL_HINT,
  6617. env_enablement_fn=hermes_env_enablement_fn,
  6618. setup_fn=hermes_setup_fn,
  6619. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  6620. standalone_sender_fn=hermes_standalone_sender_fn,
  6621. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  6622. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  6623. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  6624. emoji="😺",
  6625. allow_update_command=True,
  6626. pii_safe=False,
  6627. platform_hint=(
  6628. "Using the 'Hermes Chatto Platform Plugin' you connect to a Chatto server. "
  6629. "Authorized admins and users will contact you and call you his Hermes Agent. They are "
  6630. "natural persons and thus responsible for what they do in terms of rights. You compute "
  6631. "on their behalf. They _may_ address you by @-mentioning your name. If configured, "
  6632. "you also react without a @-mention. Direct messages reach you without a mention."
  6633. "Keep responses conversational. Markdown is supported. "
  6634. "Include MEDIA:/absolute/path/to/file in your response to refer to our local files. Images "
  6635. "(.png, .jpg, .gif, .webp) arrive as inline pictures, videos (.mp4, .mov, .webm) as "
  6636. "video attachments, audio as a voice bubble, anything else as a downloadable document. "
  6637. "Do NOT use markdown image syntax for local files. Local files always go through MEDIA:. "
  6638. "Several images in one response are bundled into a single message. "
  6639. "You can also talk to Chatto unprompted: the plugin tools chatto_list_rooms, "
  6640. "chatto_send_room and chatto_send_dm post to a channel or a person's DM on your "
  6641. "behalf. Only send into a channel that the bot answers in, and reach a person by DM "
  6642. "only once they have written to the bot themselves. "
  6643. "chatto_get_history and chatto_get_message read instead of posting: use them to "
  6644. "look up what was said in a room or thread, and to resolve an event ID you were given. "
  6645. "chatto_search_messages finds messages by their words when you do not know the room, "
  6646. "thread or day — it only answers when the server has search enabled, and says so when "
  6647. "it has not. "
  6648. ),
  6649. )