adapter.py 295 KB

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