adapter.py 300 KB

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