adapter.py 241 KB

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