adapter.py 261 KB

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