adapter.py 183 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534
  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. from collections import deque
  26. from collections.abc import AsyncIterator, Callable
  27. from contextlib import asynccontextmanager
  28. from dataclasses import dataclass, field
  29. from datetime import UTC, datetime
  30. from difflib import SequenceMatcher
  31. from enum import StrEnum
  32. from typing import Any, Final, NamedTuple
  33. from urllib.parse import unquote, urlsplit
  34. import httpx
  35. logger = logging.getLogger(__name__)
  36. from gateway.config import Platform, PlatformConfig
  37. from gateway.platforms.base import (
  38. BasePlatformAdapter,
  39. MessageEvent,
  40. MessageType,
  41. ProcessingOutcome,
  42. SendResult,
  43. cache_media_bytes,
  44. get_inbound_media_max_bytes,
  45. validate_inbound_media_size,
  46. )
  47. from gateway.session import build_session_key
  48. # Chattolib imports (vendored)
  49. # Using vendored chattolib from vendor/chattolib/
  50. # See vendor_chattolib.sh for how to update the vendored copy
  51. # Absolute imports — vendor/ is on sys.path (see above) and chattolib's own
  52. # modules import each other absolutely. Mixing in relative ".vendor.chattolib"
  53. # imports would load a second, distinct copy of every module, so isinstance()
  54. # checks across the two copies would silently fail.
  55. try:
  56. from chattolib._pb.chatto.realtime.v1 import ( # noqa: F401 — importability probe
  57. realtime_pb2,
  58. )
  59. from chattolib._pb.chatto.realtime.v1.events_pb2 import (
  60. MessagePostedEvent, # type: ignore[import-untyped]
  61. )
  62. from chattolib.client import (
  63. ChattoClient,
  64. )
  65. from chattolib.exceptions import (
  66. ChattoAuthError,
  67. ChattoError,
  68. )
  69. from chattolib.realtime import (
  70. ChattoRealtimeCloseError,
  71. ChattoRealtimeError,
  72. RealtimeEvent,
  73. stream_events,
  74. )
  75. from chattolib.types import (
  76. Message,
  77. MessageAttachment,
  78. PresenceStatus,
  79. Room,
  80. RoomKind,
  81. RoomWithViewerState,
  82. User,
  83. )
  84. except ImportError as e:
  85. # Fail loudly: continuing here only defers the failure to a confusing
  86. # NameError somewhere deep in the adapter.
  87. logger.error("Chatto: failed to import vendored chattolib: %s", e)
  88. raise
  89. try:
  90. from .platform_config import (
  91. ChattoConfiguration,
  92. ChattoConstants,
  93. )
  94. except ImportError: # pragma: no cover - loaded as a top-level module (tests)
  95. from platform_config import (
  96. ChattoConfiguration,
  97. ChattoConstants,
  98. )
  99. # --------------------------------------------------------------------------- #
  100. # Chat types
  101. # --------------------------------------------------------------------------- #
  102. class HermesChatType(StrEnum):
  103. """The ``chat_type`` vocabulary the Hermes gateway understands.
  104. Declared in ``gateway/session.py:161`` as ``"dm", "group", "channel",
  105. "thread"`` and consumed as a bare string all over the gateway:
  106. ``SessionSource.description`` (session.py:239) and the PII-redacting
  107. description in ``build_session_context_prompt`` (session.py:537) both
  108. branch on these exact values and fall back to a nameless generic case for
  109. anything else, and ``build_session_key`` puts the value straight into the
  110. session key. Passing a chattolib ``RoomKind`` (``"ROOM_KIND_CHANNEL"``)
  111. therefore does not fail loudly — it just quietly degrades what the agent is
  112. told about where it is.
  113. A StrEnum so it stays a drop-in ``str`` at every one of those call sites.
  114. GROUP vs CHANNEL
  115. ----------------
  116. There is no strict contract between the two, and the adapters disagree in
  117. practice: Slack labels every non-DM conversation ``"group"`` (including real
  118. channels), Discord uses both, and Telegram reserves ``"channel"`` for actual
  119. broadcast channels. The intended reading is ``group`` = ordinary
  120. multi-participant chat, ``channel`` = broadcast surface.
  121. The distinction only changes behaviour in three places:
  122. 1. Authorization (``gateway/authz_mixin.py``) — the only security-relevant
  123. one. The group-scoped env allowlists apply to ``{"group", "forum"}``
  124. ONLY, never to ``"channel"``: ``{PLATFORM}_GROUP_ALLOWED_USERS`` /
  125. ``_GROUP_ALLOWED_CHATS`` (:616), the chat-id allowlist (:708) and the
  126. Telegram legacy shim (:724). The adapter-delegation paths in turn treat
  127. all three alike (:461, :649, :674, :694), where the value only picks
  128. ``group_allow_from`` over ``allow_from`` from ``config.extra``.
  129. For Chatto both choices are equivalent today: those group env maps hold
  130. Telegram and QQBot only (:535-541), and our own allowlist runs through
  131. ``CHATTO_ALLOWED_USERS``, which is chat_type-independent.
  132. 2. What the agent is told — ``SessionSource.description`` renders
  133. ``"group: Name"`` vs ``"channel: Name"`` (session.py:239-246), likewise
  134. the PII-redacted variant (session.py:537-544).
  135. 3. The session key, which embeds the literal (session.py:1192). Changing
  136. the value for a room re-buckets its existing sessions.
  137. Explicitly NOT affected: ``is_shared_multi_user_session`` (session.py:1063)
  138. only looks at ``"dm"`` and ``thread_id``, so sender prefixes, the multi-user
  139. prompt line and ``group_sessions_per_user`` treat group and channel
  140. identically.
  141. """
  142. DM = "dm"
  143. GROUP = "group"
  144. CHANNEL = "channel"
  145. # Emitted by adapters whose thread events are their own chat type (Slack,
  146. # Discord). We don't: a Chatto thread keeps its room's chat_type and is
  147. # identified by ``thread_id`` on the source instead. Listed for the record,
  148. # because build_session_key rewrites the slot to "thread" itself
  149. # (session.py:1190).
  150. THREAD = "thread"
  151. # Not declared in session.py:161 but real: Telegram forum topics travel as
  152. # "forum", and the authz group allowlists above accept it alongside "group".
  153. # Chatto has no equivalent, so we never emit it.
  154. # Chatto only distinguishes DMs from channels. UNSPECIFIED means the server
  155. # sent a kind this vendored chattolib doesn't know: map it to the generic
  156. # multi-user bucket rather than guessing "channel", and never to "dm" — that
  157. # value drives session isolation (is_shared_multi_user_session, session.py:1063)
  158. # and would silently turn a room into a private conversation.
  159. #
  160. # CHANNEL for RoomKind.CHANNEL is the descriptive choice and carries no
  161. # behavioural cost (see the GROUP vs CHANNEL note above). Switching to GROUP for
  162. # Slack parity would be this one line — plus the re-bucketing of existing
  163. # sessions that point 3 of that note describes.
  164. _ROOM_KIND_TO_CHAT_TYPE: dict[RoomKind, HermesChatType] = {
  165. RoomKind.DM: HermesChatType.DM,
  166. RoomKind.CHANNEL: HermesChatType.CHANNEL,
  167. RoomKind.UNSPECIFIED: HermesChatType.GROUP,
  168. }
  169. def chat_type_for_room_kind(kind: RoomKind | None) -> HermesChatType:
  170. """Map a chattolib RoomKind onto the gateway's chat_type vocabulary.
  171. An unknown or missing kind becomes ``GROUP`` — see ``_ROOM_KIND_TO_CHAT_TYPE``.
  172. """
  173. if kind is None:
  174. return HermesChatType.GROUP
  175. return _ROOM_KIND_TO_CHAT_TYPE.get(kind, HermesChatType.GROUP)
  176. class RoomPolicy(StrEnum):
  177. """How a channel-kind room treats an inbound message.
  178. Derived per room from ``CHATTO_REQUIRE_MENTION_ROOMS`` /
  179. ``CHATTO_OPTIONAL_MENTION_ROOMS`` — see ``_room_policy``. A StrEnum
  180. so the values log readably without a formatting dance.
  181. """
  182. # Listed for unaddressed answers: every message is dispatched, and one
  183. # aimed at a named colleague gets a 🫥 acknowledgement instead of a reply.
  184. OPEN = "open"
  185. # Listed for addressed-only participation: dispatches only messages that
  186. # mention the bot (@name or a broadcast handle); others are dropped.
  187. REQUIRE_MENTION = "require_mention"
  188. # Listed in neither config: the room is silent — not dispatched at all,
  189. # read-only like any unlisted membership.
  190. SILENT = "silent"
  191. # Blocking filesystem/network helpers. The adapter runs on the shared gateway
  192. # event loop, so file reads and HTTP downloads are pushed to a worker thread
  193. # via asyncio.to_thread — a slow disk or dead image URL must not stall every
  194. # platform's message processing.
  195. def _read_file_bytes(path: str) -> bytes:
  196. """Read a whole file synchronously (run via asyncio.to_thread)."""
  197. with open(path, "rb") as f:
  198. return f.read()
  199. def _write_file_bytes(path: str, data: bytes) -> None:
  200. """Write bytes to a file synchronously (run via asyncio.to_thread)."""
  201. with open(path, "wb") as f:
  202. f.write(data)
  203. def _normalise_outbound_text(content: str) -> str:
  204. """Normalise outgoing text for Chatto.
  205. Chatto renders Markdown natively, so there is nothing to escape or
  206. translate — the only transformations here are the ones that measurably
  207. render wrong: CRLF line endings (which show up as stray blank lines)
  208. and runs of more than two blank lines. Shared by the adapter's
  209. ``format_message`` and the standalone cron sender, so both paths render
  210. identically.
  211. """
  212. if not content:
  213. return content
  214. normalised = content.replace("\r\n", "\n").replace("\r", "\n")
  215. while "\n\n\n\n" in normalised:
  216. normalised = normalised.replace("\n\n\n\n", "\n\n\n")
  217. return normalised
  218. # --------------------------------------------------------------------------- #
  219. # Adapter
  220. # --------------------------------------------------------------------------- #
  221. # Presence as the roster block spells it. UNSPECIFIED gets no label: a server
  222. # that never tracked presence should not have the roster claim anything.
  223. _PRESENCE_LABELS = {
  224. PresenceStatus.ONLINE: "online",
  225. PresenceStatus.AWAY: "away",
  226. PresenceStatus.DO_NOT_DISTURB: "do not disturb",
  227. PresenceStatus.OFFLINE: "offline",
  228. }
  229. @dataclass
  230. class _RoomRoster:
  231. """One announced room's roster projection.
  232. A miniature of the server's room membership: which user IDs belong to
  233. the room (the users themselves live in the shared ``_user_cache``) and
  234. how many directory entries were beyond the fetch limit, rendered as
  235. ``… and N more``. Presence changes patch the cached users in place;
  236. only a membership change or reconnect discards this and refetches.
  237. """
  238. member_ids: set[str] = field(default_factory=set)
  239. unfetched: int = 0
  240. _UNSEEDED: Final = object()
  241. """Sentinel: this process has delivered nothing for that thread yet.
  242. Only in memory. It is never persisted: the session store rewrites the whole
  243. routing index per call, which is not a price worth paying once per turn, and a
  244. cursor the process can rebuild from a fetch it already makes buys nothing.
  245. """
  246. def _messages_after(history: list[Message], cursor_id: str) -> list[Message] | None:
  247. """The messages ordered after ``cursor_id``, or ``None`` if it is not there.
  248. ``None`` means the cursor fell out of the fetched window — the thread grew
  249. past the limit this lookup fetches. The caller must not then re-seed from
  250. the top: that repeats context the session already holds, which is exactly
  251. what the cursor exists to prevent.
  252. """
  253. for index, message in enumerate(history):
  254. if message.id == cursor_id:
  255. return history[index + 1 :]
  256. return None
  257. def hermes_adapter_factory(config: PlatformConfig):
  258. """Construct a ChattoAdapter from a PlatformConfig."""
  259. return ChattoAdapter(config)
  260. class ChattoAdapter(BasePlatformAdapter):
  261. """Chatto platform adapter.
  262. Receives messages via WebSocket realtime, sends via ConnectRPC.
  263. """
  264. # Read by BasePlatformAdapter.max_message_length_for_chat(), which the
  265. # gateway and the stream consumer use to chunk outgoing messages. Without
  266. # it they fall back to 4096 and split Chatto messages far earlier than
  267. # necessary — send() itself already truncates at SPLIT_THRESHOLD.
  268. MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  269. splits_long_messages = True
  270. supports_code_blocks: bool = True
  271. supports_status_text: bool = True # client.update_custom_status
  272. def __init__(self, pconfig: PlatformConfig):
  273. """Signature needs to be compatible with BasePlatformAdapter.__init__."""
  274. super().__init__(
  275. config=pconfig, platform=Platform(ChattoConstants.PLATFORM_NAME)
  276. )
  277. # "extra" has been pre-populated by Hermes from config.yaml's extra block.
  278. # --- Configuration from our configuration data class with some logic ---
  279. self.chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig)
  280. # ------ State -------
  281. # Our own user, filled in by connect(). Events arriving before connect()
  282. # completes must not blow up on an undefined attribute.
  283. self.me: User | None = None
  284. # --- Runtime state ---
  285. self._room_names: dict[str, str] = {}
  286. self._room_kinds: dict[str, RoomKind] = {}
  287. # Event IDs already processed — chattolib may redeliver events across
  288. # reconnects, so every inbound event is checked against this list.
  289. # Bounded deques: appending past the cap drops the oldest ID on its own.
  290. self._seen: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  291. # Message IDs this adapter has handed to the gateway (posted or
  292. # edit-re-dispatched). Edits of anything on this list never start a
  293. # fresh turn — that is the lock against re-answering settled
  294. # conversations by editing old messages.
  295. self._dispatched_ids: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  296. # Rooms whose member roster has been projected from the directory —
  297. # the roster is room-scoped and rides on every channel turn (threads
  298. # hold isolated sessions, so each turn needs its own copy). Together
  299. # with _rosters this is our miniature projection of server state:
  300. # presence changes patch the cached users in place; membership events
  301. # and reconnects discard a room so its next turn refetches once.
  302. self._roster_announced: deque[str] = deque(maxlen=ChattoConstants.SEEN_CAP)
  303. # Announced rooms' membership projection (see _RoomRoster).
  304. self._rosters: dict[str, _RoomRoster] = {}
  305. # Thread roots whose history has been handed to their session, mapped to
  306. # the last message ID that was delivered. Thread sessions start empty, so
  307. # the first turn into a thread seeds what came before it — a cron message
  308. # whose echo we filtered as a self-event, or chatter that predates the
  309. # bot joining. A None value means an earlier process seeded it and this
  310. # one cannot tell how far it got.
  311. #
  312. # The cursor is what makes later turns safe to seed again: the agent's
  313. # own messages never reach a session (their echo is filtered as a
  314. # self-event), so a reply it posts into a live thread via
  315. # chatto_send_room is invisible to that thread forever unless the tail
  316. # after the cursor is delivered. Re-delivering everything instead would
  317. # duplicate context on every turn. Insertion-ordered and capped like the
  318. # seen-ring; unlike the roster this is deliberately NOT discarded on
  319. # reconnect, since thread history is immutable.
  320. self._seeded_threads: dict[str, str | None] = {}
  321. # Keyed by thread root, which assumes one session per thread. With
  322. # thread_sessions_per_user turned on, each participant gets their own
  323. # session while this map stays shared, so one participant's turn moves
  324. # the cursor past the other's messages and that session is seeded once
  325. # and never again. The flag is off by default and this is the price of
  326. # switching it on; keying the map by session key would fix it and is
  327. # noted next to _thread_context_for.
  328. # session_key -> message ID currently being processed there. Written
  329. # by on_processing_start, cleared by on_processing_complete; an edit
  330. # landing on the recorded ID is a mid-run correction.
  331. self._processing: dict[str, str] = {}
  332. self._joined_room_ids: list[str] = []
  333. # Rooms the server force-joined everyone into (Room.universal) — used
  334. # only for [universal] tags in the joined-rooms log line, never for
  335. # gating.
  336. self._universal_room_ids: set[str] = set()
  337. # DM room ID -> chat partner's login, resolved once via the member
  338. # directory so the joined-rooms summary can name who a DM is with.
  339. self._dm_partners: dict[str, str] = {}
  340. # One-shot guard for the unjoined-home-channel warning in _refresh_rooms.
  341. self._home_warning_logged = False
  342. self._ws_task: asyncio.Task | None = None
  343. self._presence_task: asyncio.Task | None = None
  344. # Persistent typing indicator loops per room
  345. self._typing_tasks: dict[str, asyncio.Task] = {}
  346. # Member directory cache: user_id -> user info dict
  347. self._user_cache: dict[str, User] = {}
  348. # Handle -> does a user hold it. Cached both ways; see _mentions_someone_else.
  349. self._known_handles: dict[str, bool] = {}
  350. # Chattolib client cache and lock for async access.
  351. self._chatto_client: ChattoClient | None = None
  352. self._chatto_client_lock: asyncio.Lock = asyncio.Lock()
  353. # ------------------------------------------------------------------ #
  354. # Auth
  355. # ------------------------------------------------------------------ #
  356. async def _get_chatto_client(self: ChattoAdapter) -> ChattoClient | None:
  357. """Return the shared ChattoClient, creating and logging in on first use.
  358. The default way to get a client. The fast path is a plain attribute
  359. read; first creation runs under a lock so concurrent callers log in
  360. exactly once. Returns ``None`` when no client exists yet or creation
  361. failed (bad credentials, unreachable server) — a normal state during
  362. startup, shutdown and reconnects, not an exceptional one. Callers
  363. decide what "no client" means for them, as a guard clause:
  364. client = await self._get_chatto_client()
  365. if client is None:
  366. logger.warning("Chatto: dropping X - no client available")
  367. return
  368. """
  369. if self._chatto_client is not None:
  370. return self._chatto_client
  371. async with self._chatto_client_lock:
  372. if self._chatto_client is not None:
  373. return self._chatto_client
  374. try:
  375. client = await self._open_client(
  376. base_url=self.chatto_config.base_url.value,
  377. token=self.chatto_config.token.value,
  378. )
  379. self._chatto_client = client
  380. logger.info(
  381. "Chatto: authenticated via token to '%s'",
  382. self.chatto_config.base_url.value,
  383. )
  384. return client
  385. except ChattoAuthError as e:
  386. logger.error("Chatto: authentication failed: %s", e)
  387. return None
  388. except (ChattoError, ValueError) as e:
  389. logger.error("Chatto: failed to create client: %s", e)
  390. return None
  391. async def _require_chatto_client(self) -> ChattoClient:
  392. """Return a ChattoClient or raise RuntimeError if unavailable.
  393. The exception-flavoured variant of :meth:`_get_chatto_client`, for
  394. callers whose surrounding machinery already routes exceptions.
  395. Currently that is only the realtime event loop, whose except chain
  396. turns the raise into a logged warning plus a backed-off reconnect —
  397. no special "no client" branch needed there. Everywhere else, prefer
  398. the ``is None`` guard shown in :meth:`_get_chatto_client`.
  399. """
  400. client = await self._get_chatto_client()
  401. if client is None:
  402. raise RuntimeError("Chatto client unavailable")
  403. return client
  404. # ------------------------------------------------------------------ #
  405. # Connection
  406. # ------------------------------------------------------------------ #
  407. async def _open_client(
  408. self,
  409. *,
  410. base_url: str,
  411. token: str | None = None,
  412. ) -> ChattoClient:
  413. """Return a connected ``ChattoClient`` using a bearer token.
  414. Raises ValueError when no token is configured — caught upstream as a
  415. normal creation failure, so misconfiguration reads as a logged error
  416. instead of a crash.
  417. """
  418. if not token:
  419. raise ValueError("Chatto: CHATTO_TOKEN not configured")
  420. return ChattoClient(token=token, base_url=base_url)
  421. async def connect(self, *, is_reconnect: bool = False) -> bool:
  422. """Connect to Chatto and start the realtime event stream.
  423. BasePlatformAdapter override
  424. """
  425. logger.info("Chatto: connecting...")
  426. client = await self._get_chatto_client()
  427. if client is None:
  428. self._set_fatal_error(
  429. "connect_failed", "Chatto client not available", retryable=True
  430. )
  431. return False
  432. # Get our first own user info
  433. try:
  434. self.me = await client.me()
  435. except Exception as exc:
  436. logger.error("Chatto: failed to get user info: %s", exc)
  437. self._set_fatal_error(
  438. "chatto_auth_failed",
  439. f"Chatto auth failed: {exc}",
  440. retryable=False,
  441. )
  442. try:
  443. if self._chatto_client is not None:
  444. await self._chatto_client.close()
  445. finally:
  446. self._chatto_client = None
  447. return False
  448. # Announce online presence so the bot appears online in the member list.
  449. # The server treats this as a TTL, so _presence_refresh_loop below has to
  450. # keep re-announcing it — a single call here lapses back to offline.
  451. await self._announce_online()
  452. self._closing = False
  453. # Start background realtime WS event stream loop.
  454. self._ws_task = asyncio.create_task(
  455. self._chattolib_event_loop(),
  456. name="chatto-event-stream",
  457. )
  458. self._presence_task = asyncio.create_task(
  459. self._presence_refresh_loop(),
  460. name="chatto-presence-refresh",
  461. )
  462. self._mark_connected()
  463. logger.info(
  464. "Chatto: connected to %s as '%s' (display_name: '%s' id: '%s')",
  465. self.chatto_config.base_url.value,
  466. self.me.login,
  467. self.me.display_name,
  468. self.me.id,
  469. )
  470. return True
  471. async def _announce_online(self) -> bool:
  472. """Tell the server we are online. Returns whether the call got through.
  473. Logged at warning level on failure: a silently dropped presence call is
  474. indistinguishable from a bot that is simply not running.
  475. """
  476. client = await self._get_chatto_client()
  477. if client is None:
  478. logger.warning(
  479. "Chatto: presence refresh failed, bot may appear offline: no client"
  480. )
  481. return False
  482. try:
  483. await client.set_presence(status=PresenceStatus.ONLINE)
  484. return True
  485. except Exception as exc:
  486. logger.warning(
  487. "Chatto: presence refresh failed, bot may appear offline: %s", exc
  488. )
  489. return False
  490. async def _presence_refresh_loop(self) -> None:
  491. """Re-announce ONLINE until disconnect, since presence expires server-side.
  492. Failures are not fatal — the next tick tries again, so a blip in the
  493. presence endpoint costs at most one interval of visible offline time.
  494. """
  495. while not self._closing:
  496. await self._sleep_interruptible(ChattoConstants.PRESENCE_REFRESH_INTERVAL)
  497. if self._closing:
  498. return
  499. await self._announce_online()
  500. async def disconnect(self) -> None:
  501. """Stop WebSocket, presence refresh, typing tasks, and clear state.
  502. BasePlatformAdapter override
  503. """
  504. # No explicit offline broadcast: chattolib rejects OFFLINE outright
  505. # ("stop refreshing to go offline"), so cancelling the refresh loop
  506. # below is what actually takes the bot offline.
  507. self._closing = True
  508. # Cancel all typing tasks
  509. for chat_id in list(self._typing_tasks.keys()):
  510. await self.stop_typing(chat_id)
  511. if self._ws_task and not self._ws_task.done():
  512. self._ws_task.cancel()
  513. try:
  514. await self._ws_task
  515. except (asyncio.CancelledError, Exception):
  516. logger.debug(
  517. "Chatto: websocket task ended during disconnect", exc_info=True
  518. )
  519. self._ws_task = None
  520. if self._presence_task and not self._presence_task.done():
  521. self._presence_task.cancel()
  522. try:
  523. await self._presence_task
  524. except (asyncio.CancelledError, Exception):
  525. logger.debug(
  526. "Chatto: presence task ended during disconnect", exc_info=True
  527. )
  528. self._presence_task = None
  529. if self._chatto_client:
  530. try:
  531. await self._chatto_client.close()
  532. except Exception:
  533. logger.exception("Chatto: error closing client")
  534. finally:
  535. self._chatto_client = None
  536. logger.info("Chatto: disconnected")
  537. self._mark_disconnected()
  538. async def _seed_room(self, room_id: str) -> None:
  539. """Seed high-water mark from the newest events so a restart doesn't replay history."""
  540. try:
  541. client = await self._get_chatto_client()
  542. if client is None:
  543. logger.debug(
  544. "Chatto: _seed_room aborted - no client available for %s", room_id
  545. )
  546. return
  547. timeline_page = await client.get_room_events(room_id)
  548. for ev in timeline_page.events:
  549. if ev.id:
  550. self._mark_seen(ev.id)
  551. logger.debug(
  552. "Chatto: seeded room %s with %d events",
  553. room_id,
  554. len(timeline_page.events),
  555. )
  556. except Exception as e:
  557. logger.warning("Chatto: get room events failed for %s: %s", room_id, e)
  558. # ------------------------------------------------------------------ #
  559. # Realtime Event List
  560. # ------------------------------------------------------------------ #
  561. def _mark_seen(self, event_id: str) -> None:
  562. # The deque's maxlen evicts the oldest ID — no manual trimming.
  563. self._seen.append(event_id)
  564. def _is_seen(self, event_id: str) -> bool:
  565. return event_id in self._seen
  566. # ------------------------------------------------------------------ #
  567. # WebSocket Realtime Transport
  568. # ------------------------------------------------------------------ #
  569. def _own_handles(self) -> set[str]:
  570. """The handles that address this bot, lowercased for comparison.
  571. Chatto resolves mentions case-insensitively (FDR-006), so ``@Hermes_Bot``
  572. and ``@hermes_bot`` are the same handle everywhere in our gates.
  573. """
  574. if not self.me:
  575. return set()
  576. return {
  577. handle.lower() for handle in (self.me.login, self.me.display_name) if handle
  578. }
  579. def _mention_candidates(self, body: str) -> list[str]:
  580. """Candidate @-handles in a message body, in order of appearance.
  581. Mirrors the Chatto web frontend's extraction (apps/frontend/src/lib/
  582. mentions.ts upstream): candidates come from ``ChattoConstants.
  583. MENTION_RE`` outside code regions. Mentions inside fenced code blocks
  584. and inline code spans do not resolve upstream either, so a ``@bob``
  585. quoted in a snippet must not gate our behaviour.
  586. """
  587. without_fences = re.sub(r"(?s)(```|~~~).*?(\1|$)", " ", body)
  588. without_code = re.sub(r"`[^`\n]*`", " ", without_fences)
  589. return ChattoConstants.MENTION_RE.findall(without_code)
  590. def _mentions_me(self, body: str) -> bool:
  591. """Whether the message addresses this bot.
  592. By login, by display name, or by a broadcast handle — ``@here`` speaks
  593. to everyone present and the bot is one of them, so naming a colleague
  594. alongside it does not take the bot out of the audience. Matching is
  595. case-insensitive, like every mention resolution in Chatto.
  596. """
  597. own = self._own_handles()
  598. for handle in self._mention_candidates(body):
  599. lowered = handle.lower()
  600. if lowered in own or lowered in ChattoConstants.BROADCAST_MENTIONS:
  601. return True
  602. return False
  603. async def _handle_belongs_to_a_user(self, handle: str) -> bool:
  604. """Whether ``handle`` is the login of a real Chatto user.
  605. The API carries no mention entities — ``mention_confirmation_token`` is
  606. reserved in the message descriptor — so an @-token is only a candidate
  607. until the directory confirms it. Results are cached both ways under the
  608. lowercased handle (the mention namespace is case-insensitive per
  609. FDR-006), since the same handles recur and a miss is as reusable as a
  610. hit. Only logins are looked up: matching another user's display name,
  611. as the web frontend does against its room member list, has no directory
  612. equivalent here.
  613. """
  614. cache_key = handle.lower()
  615. known = self._known_handles.get(cache_key)
  616. if known is not None:
  617. return known
  618. client = await self._get_chatto_client()
  619. if client is None:
  620. # Unresolved means "not confirmed", so the message goes through.
  621. return False
  622. try:
  623. member = await client.admin_get_member(login=handle)
  624. except Exception as exc:
  625. logger.debug("Chatto: could not resolve handle @%s: %s", handle, exc)
  626. return False
  627. # admin_get_member returns pb_to_dict(GetMemberResponse):
  628. # {"member": {"user": {...}, ...}, "roles": [...]} when found,
  629. # or {} when not found.
  630. if not member.get("member"):
  631. self._known_handles[cache_key] = False
  632. return False
  633. from chattolib.types import User
  634. user = User.parse(member["member"].get("user"))
  635. self._known_handles[cache_key] = user is not None
  636. return user is not None
  637. async def _mentions_someone_else(self, body: str) -> bool:
  638. """Whether the message @-mentions a person who is not this bot.
  639. Broadcast handles are not a person — they address everyone present,
  640. the bot included, so they do not count as someone else. A handle no
  641. user holds is not a mention at all: someone writing *about* mentioning
  642. ("per @-mention", "@nonexistent") is talking to us, and staying silent
  643. on a false positive is worse than answering one.
  644. """
  645. own = self._own_handles()
  646. for handle in self._mention_candidates(body):
  647. lowered = handle.lower()
  648. if lowered in ChattoConstants.BROADCAST_MENTIONS:
  649. continue
  650. if lowered in own:
  651. continue
  652. if await self._handle_belongs_to_a_user(handle):
  653. return True
  654. return False
  655. def _check_auth(self, user: User) -> bool:
  656. """Whether this Chatto user may talk to the agent.
  657. Deliberately our own gate instead of the gateway's authz_mixin: its
  658. group allowlists key on chat_type and per-platform env vars
  659. (``{PLATFORM}_GROUP_ALLOWED_USERS``), none of which fit Chatto's one
  660. flat member directory. ``CHATTO_ALLOWED_USERS`` matches login and id,
  661. ``CHATTO_ALLOW_ALL_USERS`` overrides both — the gate stays
  662. chat_type-independent by design.
  663. """
  664. if self._is_authorized(user.id, user.login):
  665. return True
  666. logger.warning(
  667. "Chatto: rejecting message from unauthorized user '%s' (%s)",
  668. user.login,
  669. user.id,
  670. )
  671. return False
  672. # ------------------------------------------------------------------ #
  673. # Room management over DM (/join, /leave)
  674. # ------------------------------------------------------------------ #
  675. _DM_COMMANDS = ("/join", "/leave")
  676. async def _handle_dm_command(self, room_id: str, body: str) -> bool:
  677. """Run a ``/join`` or ``/leave`` admin command sent as a direct message.
  678. Returns True when ``body`` is one of the commands — whether it
  679. succeeded or not — so the caller keeps it out of the agent pipeline.
  680. Membership lives on the Chatto server: a joined room reappears in
  681. every future ``list_rooms()`` and therefore survives restarts.
  682. """
  683. verb, _, argument = body.strip().partition(" ")
  684. if verb.lower() not in self._DM_COMMANDS:
  685. return False
  686. client = await self._get_chatto_client()
  687. if client is None:
  688. await self.send(chat_id=room_id, content="Chatto client is not connected.")
  689. return True
  690. argument = argument.strip()
  691. if not argument:
  692. await self.send(
  693. chat_id=room_id,
  694. content="Usage: /join <room-id or #name> | /leave <room-id or #name>",
  695. )
  696. return True
  697. error, target = await self._resolve_room_target(client, argument)
  698. if error or target is None:
  699. await self.send(chat_id=room_id, content=error or "Room lookup failed.")
  700. return True
  701. if verb.lower() == "/join":
  702. reply = await self._run_join(client, target)
  703. else:
  704. reply = await self._run_leave(client, target)
  705. await self.send(chat_id=room_id, content=reply)
  706. return True
  707. async def _resolve_room_target(
  708. self,
  709. client: ChattoClient,
  710. argument: str,
  711. ) -> tuple[str | None, RoomWithViewerState | None]:
  712. """Resolve a ``/join`` or ``/leave`` argument to a room.
  713. ``#name`` is looked up case-insensitively in a fresh directory scan
  714. (which also refreshes our name/kind caches); anything else is treated
  715. as a room ID and verified via GetRoom. An ambiguous name comes back as
  716. an error naming the candidates, so the admin can retry with an ID.
  717. """
  718. if not argument.startswith("#"):
  719. state = await client.get_room(argument)
  720. if state is None or state.room is None:
  721. return f"No room with ID '{argument}'.", None
  722. return None, state
  723. wanted = argument[1:].strip().casefold()
  724. # (state, room) pairs: a listed match's room is already narrowed here,
  725. # so the candidate listing below needs no fresh Optional dance.
  726. matches: list[tuple[RoomWithViewerState, Room]] = []
  727. for state in await client.list_rooms() or []:
  728. room_obj = state.room if state else None
  729. if room_obj and (room_obj.name or "").strip().casefold() == wanted:
  730. matches.append((state, room_obj))
  731. self._room_names[room_obj.id] = room_obj.name
  732. self._room_kinds[room_obj.id] = room_obj.kind
  733. if not matches:
  734. return f"No room named '{argument}'.", None
  735. if len(matches) > 1:
  736. candidates = "\n".join(f"• {room.name} ({room.id})" for _, room in matches)
  737. return (
  738. f"Several rooms are named '{argument}' — pick one by ID:\n{candidates}"
  739. ), None
  740. return None, matches[0][0]
  741. async def _run_join(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  742. """Join a room via RoomService/JoinRoom and track it as joined.
  743. An account that already holds membership (invited natively in Chatto)
  744. needs no JoinRoom call — it only gets seeded and added to the list.
  745. Channel-kind rooms additionally report their mention-list status,
  746. because a channel on neither list stays silent and this reply is
  747. where users copy the room ID from (see ``_room_join_hint``).
  748. """
  749. room_obj = state.room
  750. if room_obj is None:
  751. # Unreachable via _resolve_room_target: both of its paths only
  752. # return states whose room they already inspected.
  753. return "Chatto returned an empty room record — try again."
  754. label = f"'{room_obj.name}' ({room_obj.id})"
  755. joined_room = room_obj
  756. if not state.viewer_state.is_member:
  757. try:
  758. joined_room = await client.join_room(room_obj.id) or room_obj
  759. except ChattoError as exc:
  760. logger.warning("Chatto: /join failed for %s (%s)", room_obj.id, exc)
  761. return f"Could not join {label}: {exc}"
  762. self._room_names[joined_room.id] = joined_room.name
  763. self._room_kinds[joined_room.id] = joined_room.kind
  764. if joined_room.id not in self._joined_room_ids:
  765. # Same rule as _refresh_rooms: silent rooms are joined read-only
  766. # — seeding history nothing will ever answer would be waste.
  767. if self._answers_in_room(joined_room.id):
  768. await self._seed_room(joined_room.id)
  769. else:
  770. logger.info(
  771. "Chatto: %s is on neither mention list - joined read-only",
  772. label,
  773. )
  774. self._joined_room_ids.append(joined_room.id)
  775. if room_obj.kind != RoomKind.DM:
  776. head = (
  777. f"Already a member of {label}."
  778. if state.viewer_state.is_member
  779. else f"Joined {label}."
  780. )
  781. return f"{head}\n{self._room_join_hint(room_obj.id)}"
  782. if state.viewer_state.is_member:
  783. return f"Already a member of {label} — listening there."
  784. return f"Joined {label}."
  785. async def _run_leave(self, client: ChattoClient, state: RoomWithViewerState) -> str:
  786. """Leave a room via RoomService/LeaveRoom and drop it from the joined list.
  787. Two rooms are refused: a DM conversation cannot be left, and leaving
  788. the configured home channel would silently break cron/notification
  789. delivery, which posts there through the standalone sender.
  790. """
  791. room_obj = state.room
  792. if room_obj is None:
  793. # Same invariant as _run_join: _resolve_room_target pre-inspects.
  794. return "Chatto returned an empty room record — try again."
  795. label = f"'{room_obj.name}' ({room_obj.id})"
  796. if room_obj.kind == RoomKind.DM:
  797. return "Direct messages cannot be left."
  798. home_id = (self.chatto_config.home_channel.value or "").strip()
  799. if home_id == room_obj.id:
  800. return (
  801. f"{label} is the configured home channel "
  802. "(CHATTO_HOME_CHANNEL); leaving it would break cron and "
  803. "notification delivery. Point CHATTO_HOME_CHANNEL elsewhere first."
  804. )
  805. try:
  806. left = await client.leave_room(room_obj.id)
  807. except ChattoError as exc:
  808. logger.warning("Chatto: /leave failed for %s (%s)", room_obj.id, exc)
  809. return f"Could not leave {label}: {exc}"
  810. if not left:
  811. return f"Chatto refused to leave {label}."
  812. if room_obj.id in self._joined_room_ids:
  813. self._joined_room_ids.remove(room_obj.id)
  814. # We are no longer part of this audience; keep no roster for it.
  815. self._evict_roster(room_obj.id)
  816. return f"Left {label}."
  817. def _room_join_hint(self, room_id: str) -> str:
  818. """The mention-list status appended to a channel-kind /join reply.
  819. Users do not know their room IDs by heart — this reply is where they
  820. copy them from, so a silent channel names both env vars verbatim,
  821. ready to paste into ~/.hermes/.env. Configuration resolves once at
  822. gateway startup, hence the restart note.
  823. """
  824. policy = self._room_policy(room_id)
  825. if policy == RoomPolicy.REQUIRE_MENTION:
  826. return (
  827. "This channel answers only @mentions "
  828. "(listed in CHATTO_REQUIRE_MENTION_ROOMS)."
  829. )
  830. if policy == RoomPolicy.OPEN:
  831. return (
  832. "This channel answers every message "
  833. "(listed in CHATTO_OPTIONAL_MENTION_ROOMS)."
  834. )
  835. return (
  836. "This channel stays silent until you list its ID in"
  837. " ~/.hermes/.env (then restart the gateway):\n"
  838. f" CHATTO_REQUIRE_MENTION_ROOMS={room_id} <- answer only @mentions\n"
  839. f" CHATTO_OPTIONAL_MENTION_ROOMS={room_id} <- answer every message"
  840. )
  841. # ------------------------------------------------------------------ #
  842. # Inbound attachments
  843. # ------------------------------------------------------------------ #
  844. async def _download_attachment_bytes(self, url: str) -> bytes:
  845. """Download an attachment, refusing to buffer more than the gateway cap.
  846. The Content-Length header is checked first so an oversized asset is
  847. rejected before a single chunk is read; the running total is re-checked
  848. as chunks arrive, because a missing or lying header must not smuggle an
  849. unbounded body past the cap.
  850. """
  851. max_bytes = get_inbound_media_max_bytes()
  852. chunks: list[bytes] = []
  853. total = 0
  854. async with (
  855. httpx.AsyncClient(
  856. timeout=ChattoConstants.HTTP_TIMEOUT,
  857. follow_redirects=True,
  858. ) as http,
  859. http.stream("GET", url) as resp,
  860. ):
  861. resp.raise_for_status()
  862. declared = resp.headers.get("content-length")
  863. if declared:
  864. try:
  865. declared_size = int(declared)
  866. except ValueError:
  867. logger.debug("Chatto: ignoring invalid Content-Length %r", declared)
  868. else:
  869. validate_inbound_media_size(
  870. declared_size,
  871. media_type="attachment",
  872. max_bytes=max_bytes,
  873. )
  874. async for chunk in resp.aiter_bytes():
  875. total += len(chunk)
  876. validate_inbound_media_size(
  877. total,
  878. media_type="attachment",
  879. max_bytes=max_bytes,
  880. )
  881. chunks.append(chunk)
  882. return b"".join(chunks)
  883. async def _cache_attachments(
  884. self,
  885. attachments: list[MessageAttachment],
  886. ) -> tuple[list[str], list[str], list[str]]:
  887. """Download message attachments into the gateway media cache.
  888. Returns ``(media_urls, media_types, media_kinds)`` — the paths are
  889. agent-visible cache paths, exactly what ``cache_media_bytes`` yields for
  890. every other platform. A failing attachment is logged and skipped: the
  891. message itself still reaches the agent.
  892. """
  893. media_urls: list[str] = []
  894. media_types: list[str] = []
  895. media_kinds: list[str] = []
  896. for att in attachments:
  897. url = att.asset_url.url if att.asset_url else ""
  898. filename = att.filename
  899. content_type = att.content_type
  900. if not url:
  901. # Videos are announced before transcoding finishes, so the
  902. # signed URL can legitimately be missing on arrival.
  903. logger.debug(
  904. "Chatto: attachment '%s' has no asset URL yet, skipping",
  905. filename,
  906. )
  907. continue
  908. try:
  909. data = await self._download_attachment_bytes(url)
  910. cached = cache_media_bytes(
  911. data,
  912. filename=filename,
  913. mime_type=content_type,
  914. )
  915. except Exception as e:
  916. logger.warning(
  917. "Chatto: failed to cache attachment '%s' (%s): %s",
  918. filename,
  919. content_type,
  920. e,
  921. )
  922. continue
  923. if cached is None:
  924. logger.warning(
  925. "Chatto: attachment '%s' (%s) could not be cached, skipping",
  926. filename,
  927. content_type,
  928. )
  929. continue
  930. media_urls.append(cached.path)
  931. media_types.append(cached.media_type)
  932. media_kinds.append(cached.kind)
  933. return media_urls, media_types, media_kinds
  934. @staticmethod
  935. def _message_type_for_media_kinds(media_kinds: list[str]) -> MessageType:
  936. """Pick the MessageType for a set of cached attachment kinds."""
  937. if "document" in media_kinds:
  938. return MessageType.DOCUMENT
  939. if "image" in media_kinds:
  940. return MessageType.PHOTO
  941. if "video" in media_kinds:
  942. return MessageType.VIDEO
  943. if "audio" in media_kinds:
  944. return MessageType.AUDIO
  945. return MessageType.TEXT
  946. async def _room_kind_for(
  947. self, client: ChattoClient, room_id: str
  948. ) -> RoomKind | None:
  949. """The room's kind, from cache or a fresh GetRoom lookup.
  950. Returns ``None`` when the room cannot be resolved — the caller treats
  951. that as "not dispatchable" rather than guessing a kind.
  952. """
  953. kind = self._room_kinds.get(room_id)
  954. if kind is not None:
  955. return kind
  956. room_viewer_state = await client.get_room(room_id)
  957. if room_viewer_state is None or room_viewer_state.room is None:
  958. return None
  959. kind = room_viewer_state.room.kind or RoomKind.UNSPECIFIED
  960. self._room_kinds[room_id] = kind
  961. return kind
  962. def _room_policy(self, room_id: str) -> RoomPolicy:
  963. """Which of the mention lists a channel-kind room is on.
  964. The two lists are mutually exclusive (enforced by
  965. ``hermes_validate_config``), so membership decides: optional beats
  966. require in the face of contradictory runtime config, and a room on
  967. neither list stays silent. Callers that only need yes/no ask
  968. ``_answers_in_room``, which delegates to the shared ``_room_answers_in``
  969. the send tools use.
  970. """
  971. if room_id in self.chatto_config.optional_mention_rooms.value:
  972. return RoomPolicy.OPEN
  973. if room_id in self.chatto_config.require_mention_rooms.value:
  974. return RoomPolicy.REQUIRE_MENTION
  975. return RoomPolicy.SILENT
  976. def _answers_in_room(self, room_id: str) -> bool:
  977. """Whether inbound messages from this room reach the agent pipeline.
  978. Delegates to the shared ``_room_answers_in``, which the send tools gate
  979. on too — see there for the rule and why it exists only once. A room
  980. that answers is never read-only (its policy is not SILENT), and an
  981. unknown kind falls through to the mention lists rather than being
  982. mistaken for a DM.
  983. """
  984. return _room_answers_in(
  985. self.chatto_config, room_id, self._room_kinds.get(room_id)
  986. )
  987. async def _room_roster_context(
  988. self, client: ChattoClient, room_id: str
  989. ) -> _RoomRoster | None:
  990. """Fetch the room's member roster as a fresh projection.
  991. The agent only ever sees its prompt: without this block it cannot know
  992. who else is in a channel, because unaddressed messages are dropped by
  993. mention gating long before they could teach it a name. Fetched users go
  994. into _user_cache so presence patching and mention resolution share one
  995. store. Returns ``None`` on failure or when nothing renderable remains —
  996. best-effort by design, a directory hiccup must never cost the turn.
  997. """
  998. try:
  999. # list_room_members() in 0.5.0b4 returns member IDs only;
  1000. # batch_get_room_members() hydrates them into DirectoryMember.
  1001. member_id_list, page = await client.list_room_members(
  1002. room_id, limit=ChattoConstants.ROSTER_MEMBER_LIMIT
  1003. )
  1004. if not member_id_list:
  1005. return None
  1006. members = await client.batch_get_room_members(room_id, member_id_list)
  1007. except Exception:
  1008. logger.debug(
  1009. "Chatto: could not list members of room %s", room_id, exc_info=True
  1010. )
  1011. return None
  1012. logger.debug(
  1013. "Chatto: roster for room %s: %d members fetched, total_count=%d",
  1014. room_id,
  1015. len(members),
  1016. page.total_count,
  1017. )
  1018. member_ids: set[str] = set()
  1019. users: list[User] = []
  1020. for member in members:
  1021. user = member.user
  1022. if user is None or user.deleted:
  1023. continue
  1024. member_ids.add(user.id)
  1025. self._user_cache[user.id] = user
  1026. users.append(user)
  1027. entries = [
  1028. entry for entry in (self._roster_entry(user) for user in users) if entry
  1029. ]
  1030. if not entries:
  1031. logger.debug(
  1032. "Chatto: roster for room %s empty after filtering "
  1033. "(%d fetched, all deleted/self/without user)",
  1034. room_id,
  1035. len(members),
  1036. )
  1037. return None
  1038. logger.debug("Chatto: roster for room %s: %d entries", room_id, len(entries))
  1039. unfetched = max(0, page.total_count - len(members))
  1040. return _RoomRoster(member_ids=member_ids, unfetched=unfetched)
  1041. def _roster_entry(self, user: User) -> str:
  1042. """One roster entry, e.g. ``@bob (Bob Example, online)``.
  1043. Skips deleted users and our own account (the agent knows itself);
  1044. display name and presence are optional parts of the parenthetical.
  1045. """
  1046. if user.deleted:
  1047. return ""
  1048. if self.me is not None and user.id == self.me.id:
  1049. return ""
  1050. entry = f"@{user.login}"
  1051. details = [
  1052. part
  1053. for part in (
  1054. user.display_name,
  1055. _PRESENCE_LABELS.get(user.presence_status, ""),
  1056. )
  1057. if part
  1058. ]
  1059. if details:
  1060. entry += f" ({', '.join(details)})"
  1061. return entry
  1062. def _roster_line(self, room_id: str) -> str:
  1063. """Render the room's roster line from its cached projection."""
  1064. roster = self._rosters.get(room_id)
  1065. if roster is None:
  1066. return ""
  1067. users = [self._user_cache.get(member_id) for member_id in roster.member_ids]
  1068. entries = [
  1069. entry
  1070. for entry in (
  1071. self._roster_entry(user) for user in users if user is not None
  1072. )
  1073. if entry
  1074. ]
  1075. more = f" … and {roster.unfetched} more" if roster.unfetched else ""
  1076. return ", ".join(entries) + more
  1077. def _announce_roster(self, room_id: str, roster: _RoomRoster) -> None:
  1078. """Record a freshly fetched roster as the room's projection.
  1079. Bounded like _dispatched_ids: appending past the cap drops the oldest
  1080. room's projection alongside its deque entry.
  1081. """
  1082. if room_id not in self._roster_announced:
  1083. oldest = (
  1084. self._roster_announced.popleft()
  1085. if len(self._roster_announced) == self._roster_announced.maxlen
  1086. else None
  1087. )
  1088. self._roster_announced.append(room_id)
  1089. if oldest is not None:
  1090. self._rosters.pop(oldest, None)
  1091. self._rosters[room_id] = roster
  1092. async def _thread_context_for(
  1093. self,
  1094. client: ChattoClient,
  1095. *,
  1096. room_id: str,
  1097. thread_root_event_id: str,
  1098. current_message_id: str,
  1099. source: Any,
  1100. ) -> str:
  1101. """The thread's earlier messages, delivered once per thread.
  1102. A Hermes thread session is keyed on the thread root and starts empty,
  1103. so the turn that opens a thread is answered with nothing but the reply
  1104. itself. The reported case: a cron job posts into a channel, its echo
  1105. is filtered as a self-event and never reaches a session, and a human
  1106. replies — rooting a thread whose root the agent has never seen. Without
  1107. this block the agent answers a message it cannot read.
  1108. Gated on ``thread_root_event_id``, not on the resolved ``thread_id``:
  1109. a fresh room message is anchored to itself (see _admit_and_build), and
  1110. that thread does not exist yet, so there is nothing to fetch. DMs never
  1111. thread and never seed.
  1112. Seeding is asked of the session store, not just the in-memory deque:
  1113. the marker is process-local and dies on every restart, while the
  1114. thread's session lives in state.db — so a restart would otherwise
  1115. re-seed every thread in the room and duplicate a context the session
  1116. already holds. The deque remains as a cheap timing pre-check for two
  1117. turns racing before the first session is written.
  1118. Best-effort by design, like the roster: a failed lookup leaves the
  1119. thread unseeded so the next turn retries.
  1120. """
  1121. if not thread_root_event_id:
  1122. return ""
  1123. delivered_to = self._seeded_threads.get(thread_root_event_id, _UNSEEDED)
  1124. history = await self._thread_history(
  1125. client, room_id=room_id, thread_root_event_id=thread_root_event_id
  1126. )
  1127. if history is None:
  1128. logger.debug(
  1129. "Chatto: dispatching into thread %s without history (lookup failed)",
  1130. thread_root_event_id,
  1131. )
  1132. return ""
  1133. if delivered_to is _UNSEEDED:
  1134. if not self._thread_session_exists(source):
  1135. # First turn into this thread: the session starts empty, so hand
  1136. # it the whole thread before the reply.
  1137. earlier = [m for m in history if m.id != current_message_id]
  1138. self._record_thread_seeded(
  1139. thread_root_event_id,
  1140. self._seeded_through(history, earlier, current_message_id),
  1141. )
  1142. return self._thread_context_block(earlier)
  1143. # An earlier process answered in this thread and its session
  1144. # survived, so the cursor died with that process. Rather than
  1145. # persist one (the store rewrites the whole routing index per call,
  1146. # which is not a price worth paying per turn), reconstruct the
  1147. # partition from the fetch already being done: the newest message
  1148. # that is not ours is the last one the session certainly holds,
  1149. # because every other person's message arrives as its own turn.
  1150. delivered_to = self._last_other_party_message(history)
  1151. if delivered_to is None:
  1152. return ""
  1153. elif not isinstance(delivered_to, str):
  1154. return ""
  1155. return self._seed_thread_tail(
  1156. thread_root_event_id, history, delivered_to, current_message_id
  1157. )
  1158. def _last_other_party_message(self, history: list[Message]) -> str | None:
  1159. """The newest message in ``history`` that is not the bot's own, or None.
  1160. The partition point a lost cursor is rebuilt from. Every other person's
  1161. message became a turn of its own and is in the session; the bot's own
  1162. messages are the ones that never are, so everything after this point is
  1163. what the session is missing.
  1164. """
  1165. me = self.me
  1166. for message in reversed(history):
  1167. if me is None or message.actor_id != me.id:
  1168. return message.id
  1169. return None
  1170. @staticmethod
  1171. def _seeded_through(
  1172. history: list[Message], delivered: list[Message], current_message_id: str
  1173. ) -> str:
  1174. """How far this turn's session now reaches, for the cursor.
  1175. The trigger is excluded from the *block* — it is the message text — but
  1176. the session holds it, so the cursor passes it too. Leaving it behind
  1177. would hand the next turn the previous question a second time, as an
  1178. `[Earlier in this thread]` line beside the conversation that already
  1179. contains it. Only when the fetched window does not list the trigger: a
  1180. cursor beyond the window would be unreachable, so fall back to what was
  1181. actually delivered.
  1182. """
  1183. if any(m.id == current_message_id for m in history):
  1184. return current_message_id
  1185. return delivered[-1].id if delivered else current_message_id
  1186. def _seed_thread_tail(
  1187. self,
  1188. thread_root_event_id: str,
  1189. history: list[Message],
  1190. delivered_to: str,
  1191. current_message_id: str,
  1192. ) -> str:
  1193. """Deliver only what landed in an already-seeded thread since the cursor.
  1194. This is the agent's own output the session never saw: a message it posted
  1195. into the thread through a tool, whose realtime echo is filtered as a
  1196. self-event. Without it the next human message in that thread is answered
  1197. by an agent that does not know what it said.
  1198. """
  1199. tail = _messages_after(history, delivered_to)
  1200. if tail is None:
  1201. # The cursor is no longer in the fetched window, so the thread grew
  1202. # past it and this process cannot tell what the session already has.
  1203. # Delivering nothing repeats the old behaviour; re-seeding from the
  1204. # top would duplicate history the session holds.
  1205. logger.debug(
  1206. "Chatto: thread %s grew past the seeded cursor %s; no tail delivered",
  1207. thread_root_event_id,
  1208. delivered_to,
  1209. )
  1210. return ""
  1211. unseen = [m for m in tail if m.id != current_message_id]
  1212. # The cursor moves even when the trigger was all that arrived: it is in
  1213. # the session, and a cursor left behind it would hand the next turn the
  1214. # previous question a second time.
  1215. self._record_thread_seeded(
  1216. thread_root_event_id,
  1217. self._seeded_through(history, unseen, current_message_id),
  1218. )
  1219. return self._thread_context_block(unseen)
  1220. async def _thread_history(
  1221. self, client: ChattoClient, *, room_id: str, thread_root_event_id: str
  1222. ) -> list[Message] | None:
  1223. """Fetch a thread's messages oldest-first, or ``None`` if the lookup failed.
  1224. The thread root is fetched explicitly when the timeline omits it: a
  1225. cron message is a plain room message until someone replies to it, and
  1226. whether the server lists it back as the thread's first event is not
  1227. something the client signature promises.
  1228. """
  1229. try:
  1230. page = await client.get_thread_events(
  1231. room_id,
  1232. thread_root_event_id,
  1233. limit=ChattoConstants.THREAD_CONTEXT_MESSAGE_LIMIT,
  1234. )
  1235. except Exception:
  1236. logger.debug(
  1237. "Chatto: get thread events failed for %s/%s",
  1238. room_id,
  1239. thread_root_event_id,
  1240. exc_info=True,
  1241. )
  1242. return None
  1243. messages = [ev.message for ev in page.events if ev.message is not None]
  1244. if not any(m.id == thread_root_event_id for m in messages):
  1245. messages = (
  1246. await self._thread_root_message(
  1247. client, room_id=room_id, thread_root_event_id=thread_root_event_id
  1248. )
  1249. + messages
  1250. )
  1251. # The server's ordering is not a contract we build on — sort by the
  1252. # timestamp each message carries, so the block reads like the thread.
  1253. return sorted(
  1254. messages,
  1255. key=lambda m: m.created_at or datetime.min.replace(tzinfo=UTC),
  1256. )
  1257. async def _thread_root_message(
  1258. self, client: ChattoClient, *, room_id: str, thread_root_event_id: str
  1259. ) -> list[Message]:
  1260. """The thread root as a list, so a miss concatenates cleanly.
  1261. Best-effort: an unknown root costs nothing but the missing root line.
  1262. """
  1263. try:
  1264. root = await client.get_message(
  1265. room_id=room_id, event_id=thread_root_event_id
  1266. )
  1267. except Exception:
  1268. logger.debug(
  1269. "Chatto: get thread root failed for %s/%s",
  1270. room_id,
  1271. thread_root_event_id,
  1272. exc_info=True,
  1273. )
  1274. return []
  1275. return [root] if root is not None and not root.deleted_at else []
  1276. def _record_thread_seeded(
  1277. self, thread_root_event_id: str, last_delivered_id: str
  1278. ) -> None:
  1279. """Note that this thread's session holds its history up to that message.
  1280. Re-inserting keeps the map insertion-ordered, which is what the cap below
  1281. evicts from: the least recently touched thread.
  1282. """
  1283. self._seeded_threads.pop(thread_root_event_id, None)
  1284. self._seeded_threads[thread_root_event_id] = last_delivered_id
  1285. while len(self._seeded_threads) > ChattoConstants.SEEN_CAP:
  1286. self._seeded_threads.pop(next(iter(self._seeded_threads)))
  1287. def _thread_session_exists(self, source: Any) -> bool:
  1288. """Whether the gateway already has a session for this source.
  1289. The gateway's own routing index is the authority on "does this thread's
  1290. conversation already exist" — it is persistent (state.db), so unlike
  1291. the in-memory deque it answers correctly after a restart. Returns False
  1292. when no store is wired (tests, or a startup path before
  1293. ``set_session_store`` runs) so we fail open and seed.
  1294. """
  1295. store = getattr(self, "_session_store", None)
  1296. if store is None:
  1297. return False
  1298. return store.peek_session_id(self._session_key_for(source)) is not None
  1299. def _thread_context_block(self, messages: list[Message]) -> str:
  1300. """Render earlier thread messages as the agent's reference block.
  1301. Empty when there is nothing to say — a brand-new thread has no earlier
  1302. messages, and that is not worth a header. Over budget, the oldest
  1303. messages go first: the reply's immediate predecessors are what the
  1304. turn is about.
  1305. """
  1306. entries: list[str] = []
  1307. for message in messages:
  1308. entry = self._thread_message_entry(message)
  1309. if entry:
  1310. entries.append(entry)
  1311. if not entries:
  1312. return ""
  1313. dropped = 0
  1314. while (
  1315. entries
  1316. and len("\n".join(entries)) > ChattoConstants.THREAD_CONTEXT_CHAR_LIMIT
  1317. ):
  1318. entries.pop(0)
  1319. dropped += 1
  1320. if not entries:
  1321. return ""
  1322. body = "\n".join(entries)
  1323. omitted = f"… {dropped} earlier message(s) omitted\n" if dropped else ""
  1324. return f"{omitted}[Earlier in this thread]\n{body}"
  1325. def _thread_message_entry(self, message: Message) -> str:
  1326. """One rendered thread message, or ``""`` for one with no body.
  1327. Attachment-only messages render empty: the block is text context, and
  1328. inventing a placeholder for a picture the agent cannot see here would
  1329. be noise.
  1330. """
  1331. body = (message.body or "").strip()
  1332. if not body:
  1333. return ""
  1334. me = self.me
  1335. user = self._user_cache.get(message.actor_id)
  1336. if me is not None and message.actor_id == me.id:
  1337. # The agent's own output — often a cron message it never saw
  1338. # arrive. Labelling it keeps "I said this" distinguishable from a
  1339. # third party talking.
  1340. return f"{me.login} (this bot): {body}"
  1341. author = f"@{user.login}" if user else f"@{message.actor_id}"
  1342. if not self._is_authorized(message.actor_id, user.login if user else None):
  1343. # Auth gates the trigger message only; the rest of a shared thread
  1344. # is reference text from people who may not be on the allowlist,
  1345. # so it is marked as unverified rather than presented as trusted
  1346. # input. An unknown author lands here too — fail closed.
  1347. return f"{author} (unverified): {body}"
  1348. return f"{author}: {body}"
  1349. def _is_authorized(self, actor_id: str, login: str | None = None) -> bool:
  1350. """Whether a Chatto user may talk to the agent, by id or login.
  1351. The allowlist test itself, without the logging _check_auth adds: a
  1352. rendering path asks the same question about someone quoted into the
  1353. prompt, where denial is a normal sight rather than an event worth a
  1354. warning. Callers pass the login when they already hold the User;
  1355. otherwise it is read from the user cache.
  1356. """
  1357. if self.chatto_config.allow_all_users.value:
  1358. return True
  1359. allowed = self.chatto_config.allowed_users.value
  1360. if actor_id in allowed:
  1361. return True
  1362. if login is None:
  1363. user = self._user_cache.get(actor_id)
  1364. login = user.login if user else None
  1365. return login is not None and login in allowed
  1366. def _evict_roster(self, room_id: str) -> None:
  1367. """Drop all roster state for a room.
  1368. Called on membership changes (user_joined/left_room), when we leave a
  1369. room ourselves, and on reconnect. The subscribe snapshot carries the
  1370. room and user directory but no presence, and the adapter does not
  1371. request it — so a discarded cache is what forces one honest refetch.
  1372. """
  1373. try:
  1374. self._roster_announced.remove(room_id)
  1375. except ValueError:
  1376. pass
  1377. self._rosters.pop(room_id, None)
  1378. async def _roster_for_room(self, client: ChattoClient, *, room_id: str) -> str:
  1379. """The room's roster line for this turn — delivered on every turn.
  1380. Threads hold isolated sessions and the agent only sees
  1381. channel_context per dispatch, so each channel turn carries the current
  1382. audience rather than deduplicating it. The projection exists to spare
  1383. the directory, not the prompt: presence patches land in _user_cache
  1384. in place, membership events or a reconnect evict the room so its next
  1385. turn refetches once. An unprojected room retries on its next turn
  1386. until a lookup succeeds.
  1387. """
  1388. if room_id not in self._roster_announced:
  1389. fetched = await self._room_roster_context(client, room_id)
  1390. if fetched is None:
  1391. return ""
  1392. self._announce_roster(room_id, fetched)
  1393. return self._roster_line(room_id)
  1394. async def _dispatch_message_posted(
  1395. self, payload: MessagePostedEvent, event_id: str
  1396. ) -> None:
  1397. # Respond-room gate first: read-only memberships must not cost a
  1398. # single API call, so this runs before fetch_message and _get_chatto_client.
  1399. if not self._answers_in_room(payload.room_id):
  1400. logger.debug(
  1401. "Chatto: message from read-only room %s ignored", payload.room_id
  1402. )
  1403. return
  1404. client = await self._get_chatto_client()
  1405. if client is None:
  1406. logger.warning("Chatto: dropping message - no client available")
  1407. return
  1408. logger.debug("Chatto WS: 'message_posted' payload:%s", payload)
  1409. message = await client.get_message(room_id=payload.room_id, event_id=event_id)
  1410. if message is None or message.deleted_at:
  1411. return
  1412. message_body = message.body or ""
  1413. logger.debug("message: %s", message)
  1414. # A message carrying only an image/PDF has an empty body — dropping it
  1415. # here is what made attachments sent to Hermes disappear silently.
  1416. if not message_body and not message.attachments:
  1417. return
  1418. event = await self._admit_and_build(
  1419. client,
  1420. room_id=payload.room_id,
  1421. message=message,
  1422. source_message_id=event_id,
  1423. thread_root_event_id=payload.thread_root_event_id or None,
  1424. )
  1425. if event is None:
  1426. return
  1427. self._remember_dispatched(event.message_id or "")
  1428. logger.info("Chatto: dispatching message to Hermes")
  1429. await self.handle_message(event)
  1430. return
  1431. def _remember_dispatched(self, message_id: str) -> None:
  1432. """Record a message ID as handed to the gateway, capped like _seen."""
  1433. if not message_id:
  1434. return
  1435. self._dispatched_ids.append(message_id)
  1436. def _edit_is_fresh(self, message: Message) -> bool:
  1437. """Whether this edit is young enough to still be processed.
  1438. Age is measured against the posting time, so an edit to an hours-old
  1439. message cannot resurrect a settled conversation even when it arrives
  1440. right now.
  1441. """
  1442. if message.created_at is None or message.updated_at is None:
  1443. return True
  1444. age_seconds = (message.updated_at - message.created_at).total_seconds()
  1445. return age_seconds <= self.chatto_config.edit_window.value
  1446. def _session_key_for(self, source) -> str:
  1447. """The gateway's own session key for this source.
  1448. Built with exactly the inputs ``handle_message`` uses, so lookups in
  1449. ``_processing`` and calls to ``cancel_session_processing`` hit the
  1450. same session the gateway is running.
  1451. """
  1452. return build_session_key(
  1453. source,
  1454. group_sessions_per_user=self.config.extra.get(
  1455. "group_sessions_per_user", True
  1456. ),
  1457. thread_sessions_per_user=self.config.extra.get(
  1458. "thread_sessions_per_user", False
  1459. ),
  1460. )
  1461. async def _dispatch_message_edited(self, payload: Any) -> None:
  1462. """Route an inbound edit according to the edit-dispatch contract.
  1463. Three outcomes for the edited message:
  1464. - currently being processed → cancel that turn and re-dispatch with
  1465. the corrected text (the cancelled turn reports 🚫 via its
  1466. CANCELLED outcome hook),
  1467. - never dispatched (e.g. a forgotten @mention added later) → re-run
  1468. the admission gates against the new body and answer for real,
  1469. - already answered → stay answered.
  1470. Edits whose text parses as a DM membership command are dropped: the
  1471. command ran when the message was posted and must not run again.
  1472. """
  1473. if not self.chatto_config.edit_dispatch.value:
  1474. return
  1475. # Read-only memberships cost no API call, mirroring the posted path.
  1476. if not self._answers_in_room(payload.room_id):
  1477. logger.debug("Chatto: edit from read-only room %s ignored", payload.room_id)
  1478. return
  1479. client = await self._get_chatto_client()
  1480. if client is None:
  1481. logger.warning("Chatto: dropping edit - no client available")
  1482. return
  1483. logger.debug("Chatto WS: 'message_edited' payload:%s", payload)
  1484. message = await client.get_message(
  1485. room_id=payload.room_id, event_id=payload.message_event_id
  1486. )
  1487. if message is None or message.deleted_at:
  1488. return
  1489. message_body = message.body or ""
  1490. if not message_body and not message.attachments:
  1491. return
  1492. if not self._edit_is_fresh(message):
  1493. logger.debug(
  1494. "Chatto: edit of msg %s outside the edit window",
  1495. payload.message_event_id,
  1496. )
  1497. return
  1498. # Cheap triage before the admission pipeline: an edit to an
  1499. # already-settled message (dispatched, neither running nor queued)
  1500. # must not cost get_room/media calls or re-fire acknowledgements.
  1501. was_dispatched = payload.message_event_id in self._dispatched_ids
  1502. if (
  1503. was_dispatched
  1504. and payload.message_event_id not in self._processing.values()
  1505. and not any(
  1506. pending.message_id == payload.message_event_id
  1507. for pending in self._pending_messages.values()
  1508. )
  1509. ):
  1510. logger.debug(
  1511. "Chatto: edit of already-answered msg %s ignored",
  1512. payload.message_event_id,
  1513. )
  1514. return
  1515. event = await self._admit_and_build(
  1516. client,
  1517. room_id=payload.room_id,
  1518. message=message,
  1519. source_message_id=payload.message_event_id,
  1520. thread_root_event_id=message.thread_root_event_id or None,
  1521. allow_dm_commands=False,
  1522. )
  1523. if event is None:
  1524. return
  1525. session_key = self._session_key_for(event.source)
  1526. if self._processing.get(session_key) == payload.message_event_id:
  1527. logger.info(
  1528. "Chatto: msg %s edited mid-run - restarting the turn",
  1529. payload.message_event_id,
  1530. )
  1531. # The cancelled task's completion hook clears _processing and
  1532. # reports 🚫 before this coroutine moves on, because cancel
  1533. # awaits the task. Queued follow-ups must survive.
  1534. await self.cancel_session_processing(
  1535. session_key, release_guard=True, discard_pending=False
  1536. )
  1537. elif not was_dispatched:
  1538. logger.info(
  1539. "Chatto: msg %s was never dispatched - edit starts a fresh turn",
  1540. payload.message_event_id,
  1541. )
  1542. else:
  1543. pending = self._pending_messages.get(session_key)
  1544. if pending is not None and pending.message_id == payload.message_event_id:
  1545. # Still queued behind the running turn: correct it in place
  1546. # instead of answering stale wording later.
  1547. pending.text = event.text
  1548. logger.info(
  1549. "Chatto: queued msg %s updated to its edited text",
  1550. payload.message_event_id,
  1551. )
  1552. return
  1553. logger.debug(
  1554. "Chatto: edit of already-answered msg %s ignored",
  1555. payload.message_event_id,
  1556. )
  1557. return
  1558. self._remember_dispatched(event.message_id or "")
  1559. logger.info("Chatto: dispatching edited message to Hermes")
  1560. await self.handle_message(event)
  1561. async def _admit_and_build(
  1562. self,
  1563. client: ChattoClient,
  1564. *,
  1565. room_id: str,
  1566. message: Message,
  1567. source_message_id: str,
  1568. thread_root_event_id: str | None,
  1569. allow_dm_commands: bool = True,
  1570. ) -> MessageEvent | None:
  1571. """Run one hydrated inbound message through the admission pipeline.
  1572. Shared by the posted and the edited path: user resolution, auth,
  1573. mention gates, thread anchoring and media caching all behave
  1574. identically for both. Returns ``None`` for anything that must not
  1575. reach the agent. DM membership commands are executed here (side
  1576. effect) unless ``allow_dm_commands`` is False — edits pass False so
  1577. a corrected command line neither runs twice nor leaks to the agent.
  1578. A dispatch that opens a channel thread additionally carries the
  1579. member roster in ``channel_context`` (side effect: once the roster
  1580. was fetched, the thread root is recorded as announced).
  1581. The caller owns dispatching: a non-None result still needs
  1582. ``handle_message()``.
  1583. """
  1584. user = self._user_cache.get(message.actor_id)
  1585. if user is None:
  1586. logger.debug("Chatto: resolving user %s", message.actor_id)
  1587. member = await client.get_room_member(
  1588. room_id=message.room_id, user_id=message.actor_id
  1589. )
  1590. if member is None or member.user is None:
  1591. logger.debug(
  1592. "Chatto: dropping message from unknown user %s",
  1593. message.actor_id,
  1594. )
  1595. return None
  1596. user = member.user
  1597. self._user_cache[user.id] = user
  1598. if not self._check_auth(user):
  1599. logger.debug(
  1600. "Chatto: dropping message from user %s (auth denied)",
  1601. message.actor_id,
  1602. )
  1603. return None
  1604. room_kind = await self._room_kind_for(client, message.room_id)
  1605. if room_kind is None:
  1606. logger.debug(
  1607. "Chatto: dropping message from room %s (room_kind lookup failed)",
  1608. message.room_id,
  1609. )
  1610. return None
  1611. message_body = message.body or ""
  1612. logger.debug("message_body: %s room_kind: %s", message_body, room_kind)
  1613. # Membership commands ride in over DMs only: they change what the bot
  1614. # listens to and must never reach the agent pipeline or the mention
  1615. # gates.
  1616. if room_kind == RoomKind.DM:
  1617. if allow_dm_commands:
  1618. if await self._handle_dm_command(room_id, message_body):
  1619. return None
  1620. elif message_body.startswith("/"):
  1621. logger.debug("Chatto: edited DM command %r not re-run", message_body)
  1622. return None
  1623. # Mention gating deliberately covers everything but DMs: in a channel
  1624. # the bot is one of many listeners and must be addressed, whereas a DM
  1625. # is already addressed at it. Chatto has no group rooms — any
  1626. # multi-participant surface is a channel, and a room whose kind the
  1627. # server never set counts as one too (see _answers_in_room). The
  1628. # shared _mentions_me gate keeps this path and the someone-else check
  1629. # below on one definition of "addressed", broadcast handles included.
  1630. if room_kind != RoomKind.DM:
  1631. policy = self._room_policy(room_id)
  1632. if policy == RoomPolicy.REQUIRE_MENTION and not self._mentions_me(
  1633. message_body
  1634. ):
  1635. logger.debug(
  1636. "Chatto: dropping unaddressed message from %s (policy %s)",
  1637. room_id,
  1638. policy.value,
  1639. )
  1640. return None
  1641. # In an open channel we see every message, including ones plainly
  1642. # aimed at a named colleague. Answering those would be barging in,
  1643. # so acknowledge that we read it and stay quiet. Checked after the
  1644. # bot-mention test above, so a message naming us *and* someone
  1645. # else still counts as ours.
  1646. if (
  1647. policy == RoomPolicy.OPEN
  1648. and not self._mentions_me(message_body)
  1649. and await self._mentions_someone_else(message_body)
  1650. ):
  1651. logger.info(
  1652. "Chatto: message addresses someone else, acknowledging only"
  1653. )
  1654. if self.chatto_config.reactions.value:
  1655. await self.add_reaction(message.room_id, message.id, "🫥")
  1656. return None
  1657. # Thread anchoring — if the incoming message is inside a Chatto thread, we
  1658. # keep that thread by default; otherwise leave thread_id unset so
  1659. # replies land at the root.
  1660. thread_id = (
  1661. thread_root_event_id or None
  1662. ) # we could also take the room id but then, we're in a thread already.
  1663. if not thread_id and room_kind != RoomKind.DM:
  1664. thread_id = message.id
  1665. logger.debug(
  1666. "Chatto: thread anchoring for msg %s: incoming thread_root_event_id=%r, "
  1667. "room_kind=%s, anchored thread_id=%r",
  1668. message.id,
  1669. message.thread_root_event_id,
  1670. room_kind.name,
  1671. thread_id,
  1672. )
  1673. # Every channel turn carries the room's roster: threads hold isolated
  1674. # sessions and the agent only sees channel_context per dispatch, so a
  1675. # repeat is not deduplication but the point (see _roster_for_room).
  1676. # The gateway prepends channel_context above the message text, so the
  1677. # roster never mingles with what the user actually wrote.
  1678. source = self.build_source(
  1679. chat_id=room_id,
  1680. chat_name=self._room_names.get(message.room_id),
  1681. chat_type=chat_type_for_room_kind(room_kind),
  1682. user_id=message.actor_id,
  1683. user_name=user.login, # use login, because display_name is changeable by anyone.
  1684. thread_id=thread_id,
  1685. message_id=source_message_id,
  1686. role_authorized=True,
  1687. )
  1688. # Channel context rides ahead of the message text as read-only
  1689. # reference: the roster names the audience, the thread block carries
  1690. # what the thread already said. DMs get neither — there is no audience
  1691. # to name and no thread to catch up on. Built after the source, because
  1692. # the thread block asks the session store whether this thread's session
  1693. # already has the history (see _thread_context_for).
  1694. context_blocks: list[str] = []
  1695. if room_kind != RoomKind.DM:
  1696. logger.debug(
  1697. "Chatto: fetching roster for room %s",
  1698. room_id,
  1699. )
  1700. roster = await self._roster_for_room(client, room_id=room_id)
  1701. if roster:
  1702. context_blocks.append(roster)
  1703. else:
  1704. logger.debug(
  1705. "Chatto: dispatching channel message without roster "
  1706. "(lookup failed or empty)"
  1707. )
  1708. thread_context = await self._thread_context_for(
  1709. client,
  1710. room_id=room_id,
  1711. thread_root_event_id=thread_root_event_id or "",
  1712. current_message_id=message.id,
  1713. source=source,
  1714. )
  1715. if thread_context:
  1716. context_blocks.append(thread_context)
  1717. # prepare a MessageEvent
  1718. message_event = MessageEvent(
  1719. text=message_body,
  1720. source=source,
  1721. message_id=message.id,
  1722. timestamp=message.created_at or datetime.now(UTC),
  1723. raw_message=message,
  1724. reply_to_message_id=message.in_reply_to,
  1725. channel_context="\n\n".join(context_blocks) or None,
  1726. )
  1727. if message_event.is_command():
  1728. message_event.message_type = MessageType.COMMAND
  1729. # Attachments — download and hand the local cache paths to the gateway,
  1730. # which runs vision enrichment / document extraction off media_urls.
  1731. (
  1732. message_event.media_urls,
  1733. message_event.media_types,
  1734. media_kinds,
  1735. ) = await self._cache_attachments(list(message.attachments))
  1736. if media_kinds:
  1737. # Same precedence as the Teams/Signal adapters: document-context
  1738. # injection gates strictly on DOCUMENT, image handling keys off the
  1739. # per-path image/* MIME regardless of message_type.
  1740. message_event.message_type = self._message_type_for_media_kinds(media_kinds)
  1741. else:
  1742. message_event.message_type = MessageType.TEXT
  1743. logger.debug("Chatto: MessageEvent: %s", message_event)
  1744. return message_event
  1745. async def _forward_reaction(
  1746. self,
  1747. event: RealtimeEvent,
  1748. payload: Any,
  1749. *,
  1750. removed: bool,
  1751. ) -> None:
  1752. """Forward a human reaction to the gateway's reaction hook surface.
  1753. The handler is registered by the gateway via ``set_reaction_handler``
  1754. and fans out as ``reaction:added`` / ``reaction:removed`` through the
  1755. HookRegistry. The dict shape mirrors the Slack adapter's — hook
  1756. consumers are written against that contract, not against a per-platform
  1757. one. Our own lifecycle reactions (👀/✅/❌) are dropped: forwarding them
  1758. would feed the agent its own markers.
  1759. """
  1760. actor_id = event.actor_id
  1761. if actor_id and self.me and actor_id == self.me.id:
  1762. return
  1763. if not payload.room_id or not payload.message_event_id or not actor_id:
  1764. return
  1765. handler = self._reaction_handler
  1766. if handler is None:
  1767. return
  1768. action = "removed" if removed else "added"
  1769. try:
  1770. await handler(
  1771. {
  1772. "platform": ChattoConstants.PLATFORM_NAME,
  1773. "event_name": f"reaction:{action}",
  1774. "reaction": payload.emoji,
  1775. "user_id": actor_id,
  1776. "item_user_id": None,
  1777. "item_type": "message",
  1778. "channel_id": payload.room_id,
  1779. "message_ts": payload.message_event_id,
  1780. "event_ts": event.id,
  1781. "raw_event": event,
  1782. },
  1783. )
  1784. except Exception: # pragma: no cover - the hook contract is non-blocking
  1785. logger.debug("Chatto: reaction hook forwarding failed", exc_info=True)
  1786. async def _handle_realtime_event(self, event: RealtimeEvent) -> None:
  1787. if self._is_seen(event.id):
  1788. return
  1789. if event.actor_id is None:
  1790. return
  1791. logger.debug("EVENT happened: '%s' from %s", event.kind, event.actor_id)
  1792. # Self-event filter — the actor_id on the envelope is authoritative.
  1793. actor_id = event.actor_id
  1794. if actor_id and self.me and actor_id == self.me.id:
  1795. return
  1796. if event.kind == "message_posted":
  1797. await self._dispatch_message_posted(event.payload, event.id)
  1798. elif event.kind == "message_edited":
  1799. await self._dispatch_message_edited(event.payload)
  1800. elif event.kind in ("reaction_added", "reaction_removed"):
  1801. await self._forward_reaction(
  1802. event,
  1803. event.payload,
  1804. removed=event.kind == "reaction_removed",
  1805. )
  1806. elif event.kind == "presence_changed":
  1807. # A participant's presence changed — patch the cached user in place.
  1808. if (user := self._user_cache.get(event.payload.user_id)) is not None:
  1809. user.presence_status = event.payload.status
  1810. logger.debug(
  1811. "Chatto: patched presence of %s to %s",
  1812. event.payload.user_id,
  1813. event.payload.status.name,
  1814. )
  1815. elif event.kind in ("user_joined_room", "user_left_room"):
  1816. # Membership moved — the room's roster projection is now wrong, so
  1817. # discard it; the next turn there refetches once and re-delivers.
  1818. if event.payload.room_id in self._roster_announced:
  1819. logger.debug(
  1820. "Chatto: %s invalidated the roster of room %s",
  1821. event.kind,
  1822. event.payload.room_id,
  1823. )
  1824. self._evict_roster(event.payload.room_id)
  1825. # confirmed:
  1826. # NOTE: "projection_event" (and "caught_up") belong to realtime protocol
  1827. # v2 on unreleased Chatto main — chattolib speaks v1 and can never
  1828. # deliver them here. Revisit when vendored chattolib gains v2 typing.
  1829. elif event.kind in (
  1830. "mention_notification",
  1831. "notification_dismissed",
  1832. "room_marked_as_read",
  1833. "user_typing",
  1834. "notification_created",
  1835. "new_direct_message_notification",
  1836. "message_retracted",
  1837. "thread_created",
  1838. "thread_follow_changed",
  1839. "room_updated",
  1840. "room_groups_updated",
  1841. ):
  1842. logger.debug(
  1843. "Chatto: '%s' event received. Not yet implemented or not needed.",
  1844. event.kind,
  1845. )
  1846. else:
  1847. logger.warning("Chatto: unknown event kind: '%s'", event.kind)
  1848. async def _chattolib_event_loop(self) -> None:
  1849. """Event loop using chattolib's stream_events.
  1850. This replaces the manual WebSocket loop with chattolib's high-level
  1851. stream_events() which provides pre-decoded RealtimeEvent objects.
  1852. """
  1853. delay = ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  1854. while not self._closing:
  1855. try:
  1856. client = await self._require_chatto_client()
  1857. await self._refresh_rooms()
  1858. logger.info(
  1859. "Chatto: starting chattolib event stream with %d rooms",
  1860. len(self._joined_room_ids),
  1861. )
  1862. async for event in stream_events(client):
  1863. if self._closing:
  1864. return
  1865. if isinstance(event, RealtimeEvent):
  1866. await self._handle_realtime_event(event)
  1867. # Iterator exited cleanly — treat as a normal close and reconnect
  1868. # with the local backoff (no server hint available).
  1869. logger.info("Chatto: realtime stream ended, reconnecting")
  1870. except asyncio.CancelledError:
  1871. return
  1872. except ChattoRealtimeCloseError as exc:
  1873. if not exc.reconnect:
  1874. logger.error(
  1875. "Chatto: realtime closed by server (%s: %s), not reconnecting",
  1876. exc.code,
  1877. exc.message,
  1878. )
  1879. return
  1880. wait = max(
  1881. exc.retry_after_ms / 1000.0,
  1882. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF,
  1883. )
  1884. logger.warning(
  1885. "Chatto: realtime closed by server (%s), reconnecting in %.1fs",
  1886. exc.code,
  1887. wait,
  1888. )
  1889. delay = (
  1890. ChattoConstants.WS_RECONNECT_INITIAL_BACKOFF
  1891. ) # server hint supersedes local backoff
  1892. await self._sleep_interruptible(wait)
  1893. continue
  1894. except ChattoRealtimeError as exc:
  1895. if exc.fatal:
  1896. logger.error(
  1897. "Chatto: fatal realtime error (%s): %s", exc.code, exc.message
  1898. )
  1899. return
  1900. logger.warning(
  1901. "Chatto: realtime error (%s: %s), reconnecting in %.1fs",
  1902. exc.code,
  1903. exc.message,
  1904. delay,
  1905. )
  1906. except Exception as exc:
  1907. cause = exc.__cause__
  1908. if cause is not None and isinstance(cause, TypeError):
  1909. logger.warning(
  1910. "Chatto: realtime wire corruption (%s), reconnecting in %.1fs",
  1911. cause,
  1912. delay,
  1913. )
  1914. else:
  1915. logger.warning(
  1916. "Chatto: unexpected realtime error: %s, reconnecting in %.1fs",
  1917. exc,
  1918. delay,
  1919. )
  1920. if self._closing:
  1921. return
  1922. jitter = delay * 0.2 * random.random()
  1923. await self._sleep_interruptible(delay + jitter)
  1924. delay = min(delay * 2, ChattoConstants.WS_RECONNECT_MAX_BACKOFF)
  1925. async def _sleep_interruptible(self, seconds: float) -> None:
  1926. """Sleep in short slices so disconnect() cancels promptly."""
  1927. end = asyncio.get_running_loop().time() + seconds
  1928. while not self._closing:
  1929. remaining = end - asyncio.get_running_loop().time()
  1930. if remaining <= 0:
  1931. return
  1932. await asyncio.sleep(min(remaining, 0.5))
  1933. def _warn_if_home_channel_unjoined(self, member_ids: set[str]) -> None:
  1934. """Warn once when CHATTO_HOME_CHANNEL names a room the bot is not in.
  1935. Standalone cron delivery posts straight into that room with a fresh
  1936. client and no join logic of its own — without server-side membership
  1937. every proactive send fails there.
  1938. """
  1939. home_id = (self.chatto_config.home_channel.value or "").strip()
  1940. if (
  1941. not home_id
  1942. or home_id in member_ids
  1943. or home_id in self._joined_room_ids
  1944. or self._home_warning_logged
  1945. ):
  1946. return
  1947. self._home_warning_logged = True
  1948. logger.warning(
  1949. "Chatto: CHATTO_HOME_CHANNEL '%s' is not a joined room - cron and "
  1950. "notification delivery will fail until the bot joins it (invite "
  1951. "the account natively in Chatto, or DM it '/join').",
  1952. home_id,
  1953. )
  1954. async def _resolve_dm_partner(self, client: ChattoClient, room_id: str) -> None:
  1955. """Cache the chat partner's login for a DM room, best-effort.
  1956. DM rooms carry no usable name of their own, so the joined-rooms
  1957. summary names the other side instead. Resolved once per room and
  1958. session; without our own user (pre-connect) or on a directory error
  1959. the raw room name stays in place.
  1960. """
  1961. if room_id in self._dm_partners or self.me is None:
  1962. return
  1963. try:
  1964. member_ids, _page = await client.list_room_members(room_id)
  1965. if not member_ids:
  1966. return
  1967. members = await client.batch_get_room_members(room_id, member_ids)
  1968. except Exception:
  1969. logger.debug(
  1970. "Chatto: could not list members of DM %s", room_id, exc_info=True
  1971. )
  1972. return
  1973. for member in members:
  1974. user = member.user
  1975. if user and user.id != self.me.id:
  1976. self._dm_partners[room_id] = user.login or user.display_name
  1977. return
  1978. def _joined_room_label(self, room_id: str) -> str:
  1979. """One entry for the joined-rooms summary, with how-we-answer tags.
  1980. The tag names the room's participation mode at a glance: DMs answer
  1981. unconditionally, listed channels answer on mentions or every message,
  1982. and an unlisted channel is read-only. A DM is labelled with its chat
  1983. partner's login rather than its (empty) room name, and names are
  1984. quoted so empty strings and spaces stay visible.
  1985. """
  1986. name = self._room_names.get(room_id, room_id)
  1987. if self._room_kinds.get(room_id) == RoomKind.DM:
  1988. tags = "[dm]"
  1989. name = self._dm_partners.get(room_id) or name
  1990. else:
  1991. policy = self._room_policy(room_id)
  1992. if policy == RoomPolicy.REQUIRE_MENTION:
  1993. tags = "[on-mention]"
  1994. elif policy == RoomPolicy.OPEN:
  1995. tags = "[every-message]"
  1996. else:
  1997. tags = "[read-only]"
  1998. if room_id in self._universal_room_ids:
  1999. tags += " [universal]"
  2000. return f'"{name}" ({room_id}) {tags}'
  2001. def _log_joined_rooms(self) -> None:
  2002. """Log the joined rooms and how the bot answers in each of them."""
  2003. labels = [self._joined_room_label(rid) for rid in self._joined_room_ids]
  2004. logger.info(
  2005. "Chatto WS: currently joined in %d room(s): %s",
  2006. len(labels),
  2007. ", ".join(labels),
  2008. )
  2009. async def _refresh_rooms(self) -> None:
  2010. """Refresh room list via ConnectRPC, join and seed any newly discovered rooms.
  2011. Runs once per (re)connect, so this is also the bootstrap point for the
  2012. roster projection: nothing on the wire reports presence at connect
  2013. time (the subscribe snapshot has no presence field; presence arrives
  2014. as its own events), so cached presence could only heal on the next
  2015. random change. Discarding it makes each announced room's first turn
  2016. refetch fresh data — lazily, so quiet rooms stay free of API calls.
  2017. """
  2018. client = await self._get_chatto_client()
  2019. if client is None:
  2020. logger.warning("Chatto WS: _refresh_rooms aborted - no client available")
  2021. return
  2022. for announced in list(self._roster_announced):
  2023. self._evict_roster(announced)
  2024. try:
  2025. rooms_list = await client.list_rooms()
  2026. member_ids: set[str] = set()
  2027. new_room_ids: list[str] = []
  2028. for room_with_state in rooms_list:
  2029. if not room_with_state:
  2030. continue
  2031. room_obj = room_with_state.room or None
  2032. if not room_obj:
  2033. continue
  2034. self._room_names[room_obj.id] = room_obj.name
  2035. self._room_kinds[room_obj.id] = room_obj.kind
  2036. if room_obj.kind == RoomKind.DM:
  2037. await self._resolve_dm_partner(client, room_obj.id)
  2038. if room_obj.universal:
  2039. self._universal_room_ids.add(room_obj.id)
  2040. if not room_with_state.viewer_state.is_member:
  2041. continue
  2042. member_ids.add(room_obj.id)
  2043. if room_obj.id not in self._joined_room_ids:
  2044. new_room_ids.append(room_obj.id)
  2045. # Left via /leave, kicked, deleted: rooms we no longer belong
  2046. # to drop out here — otherwise the next refresh would quietly
  2047. # re-add what /leave just removed.
  2048. stale_room_ids = [
  2049. rid for rid in self._joined_room_ids if rid not in member_ids
  2050. ]
  2051. for rid in stale_room_ids:
  2052. self._joined_room_ids.remove(rid)
  2053. self._evict_roster(rid)
  2054. if stale_room_ids:
  2055. logger.info(
  2056. "Chatto WS: no longer a member of %d room(s): %s",
  2057. len(stale_room_ids),
  2058. stale_room_ids,
  2059. )
  2060. self._warn_if_home_channel_unjoined(member_ids)
  2061. if new_room_ids:
  2062. logger.info(
  2063. "Chatto WS: discovered %d new room(s): %s",
  2064. len(new_room_ids),
  2065. new_room_ids,
  2066. )
  2067. for rid in new_room_ids:
  2068. # Membership came straight from the directory scan
  2069. # (viewer_state.is_member); natively invited rooms need no
  2070. # JoinRoom call — same rule as _run_join.
  2071. if self._answers_in_room(rid):
  2072. await self._seed_room(rid)
  2073. else:
  2074. logger.info(
  2075. "Chatto WS: %s (%s) is on neither mention list -"
  2076. " joined read-only",
  2077. self._room_names.get(rid, rid),
  2078. rid,
  2079. )
  2080. self._joined_room_ids.append(rid)
  2081. self._log_joined_rooms()
  2082. except Exception:
  2083. logger.warning("Chatto WS: _refresh_rooms failed", exc_info=True)
  2084. # ------------------------------------------------------------------ #
  2085. # Read state (best-effort, Chatto-unique)
  2086. # ------------------------------------------------------------------ #
  2087. # Deliberately outside the try block above: this sweep runs on every
  2088. # refresh — including refreshes that discovered no new rooms. The
  2089. # old early return starved it to "only when something changed",
  2090. # leaving silent rooms unmarked for whole connection lifetimes.
  2091. # Best-effort: mark all joined rooms as read (room_id may be undefined here)
  2092. for _rid in list(self._joined_room_ids):
  2093. try:
  2094. await client.mark_room_as_read(room_id=_rid)
  2095. except Exception:
  2096. logger.debug(
  2097. "Chatto: mark_room_as_read failed for %s", _rid, exc_info=True
  2098. )
  2099. # ------------------------------------------------------------------ #
  2100. # Sending (ConnectRPC — unchanged from polling version)
  2101. # ------------------------------------------------------------------ #
  2102. def _resolve_outbound_thread(
  2103. self,
  2104. chat_id: str,
  2105. reply_to: str | None,
  2106. metadata: dict[str, Any] | None,
  2107. ) -> str | None:
  2108. """The thread an outbound message belongs in, or ``None`` for the room.
  2109. One definition for every outbound path (text and attachments):
  2110. ``metadata["thread_id"]`` wins — it names the thread root to stay in;
  2111. otherwise ``reply_to`` anchors a thread under the incoming message,
  2112. but only with ``auto_thread`` enabled. DMs never thread.
  2113. Deliberately does NOT open an auto-thread of its own — only the
  2114. chunked text path in :meth:`send` does that, because only there do
  2115. further chunks follow into the freshly created thread.
  2116. """
  2117. thread_id = (metadata or {}).get("thread_id")
  2118. if reply_to and self.chatto_config.auto_thread.value and not thread_id:
  2119. thread_id = reply_to
  2120. if self._room_kinds.get(chat_id) == RoomKind.DM:
  2121. return None
  2122. return str(thread_id) if thread_id else None
  2123. async def send(
  2124. self,
  2125. chat_id: str,
  2126. content: str,
  2127. reply_to: str | None = None,
  2128. metadata: dict[str, Any] | None = None,
  2129. ) -> SendResult:
  2130. """Send a message to a Chatto room.
  2131. Long messages are split into chunks via ``truncate_message`` and
  2132. each chunk is sent as a separate CreateMessage call. The first
  2133. chunk's message ID is returned as ``message_id``.
  2134. When ``auto_thread`` is enabled and the incoming message was a
  2135. regular room message (not already in a thread), the first chunk is
  2136. sent as a room message and its ID becomes the thread root. Subsequent
  2137. chunks are sent in that thread. This mirrors Discord's auto_thread
  2138. behavior.
  2139. BasePlatformAdapter override
  2140. """
  2141. if not content:
  2142. return SendResult(success=False, error="Empty message")
  2143. thread_id = self._resolve_outbound_thread(chat_id, reply_to, metadata)
  2144. room_kind = self._room_kinds.get(chat_id)
  2145. is_dm = room_kind == RoomKind.DM
  2146. # Auto-thread: by default, Chatto creates a thread for replies to room
  2147. # messages (not DMs, not already in a thread). This keeps conversations
  2148. # organized in the room. Can be disabled via extra.auto_thread=false.
  2149. use_auto_thread = (
  2150. self.chatto_config.auto_thread.value and not thread_id and not is_dm
  2151. )
  2152. client = await self._get_chatto_client()
  2153. if client is None:
  2154. return SendResult(
  2155. success=False, error="Chatto client not available", retryable=True
  2156. )
  2157. # The split, the routing and the stop-at-first-failure all live in
  2158. # _deliver_chunks, shared with the plugin tools: a long answer must
  2159. # reach the room the same way whoever sent it.
  2160. delivery = await _deliver_chunks(
  2161. client,
  2162. chat_id,
  2163. content,
  2164. thread_root_event_id=str(thread_id) if thread_id else "",
  2165. create_thread=use_auto_thread,
  2166. on_posted=self._mark_seen,
  2167. )
  2168. message_ids = delivery.message_ids
  2169. if use_auto_thread and message_ids and not thread_id:
  2170. thread_id = delivery.root_event_id
  2171. # Nothing got through at all — report the failure instead of a phantom success.
  2172. if not message_ids:
  2173. # Only server-side failures count as retryable; a bug in our own
  2174. # code must not read as a transient network blip.
  2175. return SendResult(
  2176. success=False,
  2177. error=(
  2178. str(delivery.error)
  2179. if delivery.error
  2180. else "Chatto: message could not be sent"
  2181. ),
  2182. retryable=isinstance(delivery.error, ChattoError),
  2183. )
  2184. first_id = message_ids[0]
  2185. # ------------------------------------------------------------------ #
  2186. # Thread following (best-effort, Chatto-unique)
  2187. # ------------------------------------------------------------------ #
  2188. if thread_id:
  2189. try:
  2190. await client.follow_thread(chat_id, thread_id)
  2191. except Exception:
  2192. logger.debug(
  2193. "Chatto: follow_thread failed for %s/%s",
  2194. chat_id,
  2195. thread_id,
  2196. exc_info=True,
  2197. )
  2198. # A later chunk failed after earlier ones went out: partial delivery.
  2199. if delivery.error is not None:
  2200. logger.warning(
  2201. "Chatto: sent %d/%d chunk(s) to %s before failing: %s",
  2202. len(message_ids),
  2203. delivery.chunks_total,
  2204. chat_id,
  2205. delivery.error,
  2206. )
  2207. # raw_response stays unset (dict-shaped per the SendResult contract):
  2208. # gateway consumers such as the cron scheduler call .get() on it, so a
  2209. # chattolib Message here would crash delivery bookkeeping *after* the
  2210. # send already succeeded — the job then falls back to the standalone
  2211. # path and the room sees the message twice.
  2212. return SendResult(success=True, message_id=first_id)
  2213. def format_message(self, content: str) -> str:
  2214. """Normalise outgoing text for Chatto.
  2215. The transformations live in :func:`_normalise_outbound_text`, shared
  2216. with the standalone cron sender.
  2217. BasePlatformAdapter override
  2218. """
  2219. return _normalise_outbound_text(content)
  2220. async def edit_message(
  2221. self,
  2222. chat_id: str,
  2223. message_id: str,
  2224. content: str,
  2225. *,
  2226. finalize: bool = False,
  2227. ) -> SendResult:
  2228. """Edit a message we previously sent, via MessageService/UpdateMessage.
  2229. The stream consumer drives streaming replies through this: without the
  2230. override the base class reports "Not supported" and every incremental
  2231. update arrives as a *new* message.
  2232. ``finalize`` is a no-op for Chatto — an edit is an edit here, there is
  2233. no in-progress card state to close out (hence no
  2234. ``REQUIRES_EDIT_FINALIZE``).
  2235. Content that exceeds the per-message limit is refused rather than
  2236. silently truncated, so the caller falls back to ``send()``, which
  2237. splits across messages.
  2238. BasePlatformAdapter override
  2239. """
  2240. if not message_id:
  2241. return SendResult(success=False, error="Chatto: no message id to edit")
  2242. if not content:
  2243. return SendResult(success=False, error="Empty message")
  2244. formatted = self.format_message(content)
  2245. if len(formatted) > ChattoConstants.MAX_MESSAGE_LENGTH:
  2246. # Refuse instead of truncating: the caller's fallback path splits.
  2247. return SendResult(
  2248. success=False,
  2249. error=(
  2250. f"Chatto: edit exceeds {ChattoConstants.MAX_MESSAGE_LENGTH} "
  2251. f"chars ({len(formatted)})"
  2252. ),
  2253. )
  2254. client = await self._get_chatto_client()
  2255. if client is None:
  2256. return SendResult(
  2257. success=False, error="Chatto client not available", retryable=True
  2258. )
  2259. try:
  2260. msg = await client.update_message(
  2261. room_id=str(chat_id),
  2262. event_id=str(message_id),
  2263. body=formatted,
  2264. )
  2265. except ChattoError as e:
  2266. logger.warning("Chatto: UpdateMessage failed for %s: %s", message_id, e)
  2267. return SendResult(success=False, error=str(e), retryable=True)
  2268. except Exception as e:
  2269. logger.warning("Chatto: UpdateMessage error for %s: %s", message_id, e)
  2270. return SendResult(success=False, error=str(e), retryable=False)
  2271. # Our own edit comes back as a message_edited event; mark it seen so it
  2272. # is never mistaken for inbound traffic.
  2273. edited_id = msg.id or str(message_id)
  2274. self._mark_seen(edited_id)
  2275. return SendResult(success=True, message_id=edited_id)
  2276. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  2277. """Delete a message via MessageService/DeleteMessage.
  2278. Used by the stream consumer's fresh-final cleanup (removing a preview
  2279. message once the completed reply has been sent) and by the ephemeral
  2280. reply TTL.
  2281. BasePlatformAdapter override
  2282. """
  2283. if not chat_id or not message_id:
  2284. return False
  2285. client = await self._get_chatto_client()
  2286. if client is None:
  2287. logger.warning("Chatto: DeleteMessage — client unavailable")
  2288. return False
  2289. try:
  2290. return bool(
  2291. await client.delete_message(
  2292. room_id=str(chat_id),
  2293. event_id=str(message_id),
  2294. )
  2295. )
  2296. except ChattoError as e:
  2297. logger.warning("Chatto: DeleteMessage failed for %s: %s", message_id, e)
  2298. return False
  2299. except Exception as e:
  2300. logger.warning("Chatto: DeleteMessage error for %s: %s", message_id, e)
  2301. return False
  2302. async def create_handoff_thread(
  2303. self,
  2304. parent_chat_id: str,
  2305. name: str,
  2306. ) -> str | None:
  2307. """Anchor a session handoff in a fresh thread under *parent_chat_id*.
  2308. Chatto threads hang off a message, not off the room, so we post a seed
  2309. message and hand its ID back as the thread root — the same shape the
  2310. Slack adapter uses. DMs don't support threads, so they get ``None``
  2311. and the watcher keeps delivering into the DM itself.
  2312. BasePlatformAdapter override
  2313. """
  2314. if not parent_chat_id:
  2315. return None
  2316. if self._room_kinds.get(parent_chat_id) == RoomKind.DM:
  2317. logger.debug("Chatto: handoff thread skipped — %s is a DM", parent_chat_id)
  2318. return None
  2319. client = await self._get_chatto_client()
  2320. if client is None:
  2321. logger.warning("Chatto: handoff thread — client unavailable")
  2322. return None
  2323. try:
  2324. msg = await client.post_message(
  2325. room_id=str(parent_chat_id),
  2326. body=f"🧵 Hermes handoff — **{(name or 'session').strip()[:80]}**",
  2327. )
  2328. except Exception as e:
  2329. logger.warning(
  2330. "Chatto: handoff thread seed-post failed for room %s: %s",
  2331. parent_chat_id,
  2332. e,
  2333. )
  2334. return None
  2335. seed_id = msg.id
  2336. if not seed_id:
  2337. logger.warning("Chatto: handoff thread seed-post returned no message id")
  2338. return None
  2339. self._mark_seen(seed_id)
  2340. try:
  2341. await client.follow_thread(str(parent_chat_id), seed_id)
  2342. except Exception:
  2343. logger.debug(
  2344. "Chatto: follow_thread failed for handoff %s/%s",
  2345. parent_chat_id,
  2346. seed_id,
  2347. exc_info=True,
  2348. )
  2349. return seed_id
  2350. # Overridden from BaseAdapter:
  2351. async def send_typing(self, chat_id: str, metadata=None) -> None:
  2352. """Start a persistent typing indicator for a room.
  2353. Sends a typing ping every 10 seconds (Chatto's indicator likely
  2354. lasts ~8-10s). The background loop runs until ``stop_typing()``
  2355. is called or the task is cancelled.
  2356. BasePlatformAdapter override
  2357. """
  2358. if chat_id in self._typing_tasks:
  2359. return # already running
  2360. async def _typing_loop() -> None:
  2361. try:
  2362. while True:
  2363. try:
  2364. client = await self._get_chatto_client()
  2365. if client is None:
  2366. return
  2367. await client.refresh_typing_indicator(room_id=str(chat_id))
  2368. except asyncio.CancelledError:
  2369. return
  2370. except Exception:
  2371. logger.debug(
  2372. "Chatto: typing indicator refresh failed for %s",
  2373. chat_id,
  2374. exc_info=True,
  2375. )
  2376. await asyncio.sleep(10)
  2377. except asyncio.CancelledError:
  2378. pass
  2379. finally:
  2380. self._typing_tasks.pop(chat_id, None)
  2381. self._typing_tasks[chat_id] = asyncio.create_task(_typing_loop())
  2382. async def stop_typing(self, chat_id: str) -> None:
  2383. """Stop the persistent typing indicator for a room.
  2384. BasePlatformAdapter override
  2385. """
  2386. task = self._typing_tasks.pop(chat_id, None)
  2387. if task:
  2388. task.cancel()
  2389. try:
  2390. await task
  2391. except (asyncio.CancelledError, Exception):
  2392. logger.debug("Chatto: typing task ended for %s", chat_id, exc_info=True)
  2393. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  2394. """Get information about a chat/room.
  2395. BasePlatformAdapter override
  2396. """
  2397. name = self._room_names.get(chat_id, chat_id)
  2398. kind = self._room_kinds.get(chat_id)
  2399. return {
  2400. "name": name,
  2401. "type": chat_type_for_room_kind(kind).value,
  2402. }
  2403. # ------------------------------------------------------------------ #
  2404. # Reactions
  2405. # ------------------------------------------------------------------ #
  2406. @staticmethod
  2407. def _emoji_to_shortcode(emoji: str) -> str:
  2408. """Convert a unicode emoji to a Chatto shortcode name.
  2409. If the emoji is already a shortcode (no unicode mapping found),
  2410. return it as-is.
  2411. """
  2412. shortcode = ChattoConstants.EMOJI_TO_SHORTCODE.get(emoji)
  2413. if shortcode:
  2414. return shortcode
  2415. # Already a shortcode like "thumbsup" — return as-is
  2416. return emoji
  2417. async def add_reaction(self, room_id: str, message_id: str, emoji: str) -> bool:
  2418. """Add a reaction to a message via MessageService/AddReaction.
  2419. BasePlatformAdapter override
  2420. """
  2421. shortcode = self._emoji_to_shortcode(emoji)
  2422. client = await self._get_chatto_client()
  2423. if client is None:
  2424. logger.warning("Chatto: AddReaction — client unavailable")
  2425. return False
  2426. try:
  2427. result = await client.add_reaction(
  2428. room_id=room_id,
  2429. message_event_id=message_id,
  2430. emoji=shortcode,
  2431. )
  2432. return result
  2433. except ChattoError as e:
  2434. logger.warning("Chatto: AddReaction failed: %s", e)
  2435. return False
  2436. except Exception as e:
  2437. logger.warning("Chatto: AddReaction error: %s", e)
  2438. return False
  2439. async def remove_reaction(self, chat_id: str, message_id: str, emoji: str) -> bool:
  2440. """Remove a reaction from a message via MessageService/RemoveReaction.
  2441. BasePlatformAdapter override
  2442. """
  2443. shortcode = self._emoji_to_shortcode(emoji)
  2444. client = await self._get_chatto_client()
  2445. if client is None:
  2446. logger.warning("Chatto: RemoveReaction — client unavailable")
  2447. return False
  2448. try:
  2449. result = await client.remove_reaction(
  2450. room_id=str(chat_id),
  2451. message_event_id=str(message_id),
  2452. emoji=shortcode,
  2453. )
  2454. return result
  2455. except ChattoError as e:
  2456. logger.warning("Chatto: RemoveReaction failed: %s", e)
  2457. return False
  2458. except Exception as e:
  2459. logger.warning("Chatto: RemoveReaction error: %s", e)
  2460. return False
  2461. # NOTE: there is deliberately no start_dm(). On Chatto only a person can
  2462. # start a DM ("Only people can start a DM... A bot cannot start a DM, even
  2463. # with message.post", dev-docs/guides/operations/permissions), and nothing
  2464. # in Hermes calls such a method — BasePlatformAdapter does not even declare
  2465. # one. An earlier version had it and advertised "DM initiation" in the
  2466. # capability banner, but it could only ever fail: the vendored chattolib's
  2467. # start_dm() calls a service stub that does not exist, so the AttributeError
  2468. # was swallowed into a silent None. DMs become usable the moment the other
  2469. # person writes to the bot; /join and the chatto_send_dm tool both say so.
  2470. # ------------------------------------------------------------------ #
  2471. # Room creation (Chatto-unique)
  2472. # ------------------------------------------------------------------ #
  2473. async def create_room(
  2474. self,
  2475. name: str,
  2476. description: str = "",
  2477. group_id: str = "",
  2478. universal: bool = True,
  2479. ) -> str | None:
  2480. """Create an ad-hoc room via RoomService/CreateRoom.
  2481. Returns the room ID on success, or None on failure.
  2482. BasePlatformAdapter override
  2483. """
  2484. client = await self._get_chatto_client()
  2485. if client is None:
  2486. return None
  2487. try:
  2488. room = await client.create_room(
  2489. name=name,
  2490. group_id=group_id or "",
  2491. description=description,
  2492. universal=universal,
  2493. )
  2494. rid = str(room.id) if room else ""
  2495. if rid:
  2496. self._room_names[rid] = room.name
  2497. self._room_kinds[rid] = room.kind
  2498. return rid
  2499. logger.debug("Chatto: CreateRoom returned no room id")
  2500. return None
  2501. except ChattoError as e:
  2502. logger.debug("Chatto: CreateRoom failed: %s", e)
  2503. return None
  2504. except Exception as e:
  2505. logger.debug("Chatto: CreateRoom error: %s", e)
  2506. return None
  2507. # ------------------------------------------------------------------ #
  2508. # Processing lifecycle hooks (reactions-based, like Discord)
  2509. # ------------------------------------------------------------------ #
  2510. def _event_room_and_message_id(self, event: MessageEvent) -> tuple[str, str]:
  2511. """Extract room_id and message_id from a MessageEvent."""
  2512. message_id = event.message_id or ""
  2513. return event.source.chat_id, message_id
  2514. async def on_processing_start(self, event: MessageEvent) -> None:
  2515. """Record the turn as open, then add an 👀 (eyes) reaction.
  2516. The record is what lets an edit of this very message be recognized as
  2517. a mid-run correction. It must be maintained even when reactions are
  2518. disabled — tracking and decorating are independent concerns.
  2519. BasePlatformAdapter override
  2520. """
  2521. session_key = (
  2522. self._session_key_for(event.source) if event.source is not None else ""
  2523. )
  2524. if session_key and event.message_id:
  2525. self._processing[session_key] = str(event.message_id)
  2526. if not self.chatto_config.reactions.value:
  2527. return
  2528. chat_id, message_id = self._event_room_and_message_id(event)
  2529. if not chat_id or not message_id:
  2530. # Routine, not a fault: the gateway runs agent-initiated turns
  2531. # (heartbeat polls, goal continuations) through the same pipeline
  2532. # with message_id=None, and there is no inbound message to mark.
  2533. logger.debug(
  2534. "Chatto: nothing to react to (chat_id=%r, message_id=%r)",
  2535. chat_id,
  2536. message_id,
  2537. )
  2538. return
  2539. await self.add_reaction(chat_id, message_id, "👀")
  2540. async def on_processing_complete(
  2541. self,
  2542. event: MessageEvent,
  2543. outcome: ProcessingOutcome,
  2544. ) -> None:
  2545. """Close the turn's record, then swap 👀 for ✅/❌/🚫.
  2546. Fires for every outcome, including CANCELLED (mid-run edit
  2547. correction) — this is what re-arms `_processing` before the corrected
  2548. turn is dispatched.
  2549. BasePlatformAdapter override
  2550. """
  2551. session_key = (
  2552. self._session_key_for(event.source) if event.source is not None else ""
  2553. )
  2554. if session_key and event.message_id:
  2555. self._processing.pop(session_key, None)
  2556. if not self.chatto_config.reactions.value:
  2557. return
  2558. chat_id, message_id = self._event_room_and_message_id(event)
  2559. if not chat_id or not message_id:
  2560. return
  2561. # Remove the processing eyes reaction
  2562. await self.remove_reaction(chat_id, message_id, "👀")
  2563. # Add the outcome reaction
  2564. if outcome == ProcessingOutcome.SUCCESS:
  2565. await self.add_reaction(chat_id, message_id, "✅")
  2566. elif outcome == ProcessingOutcome.FAILURE:
  2567. await self.add_reaction(chat_id, message_id, "❌")
  2568. elif outcome == ProcessingOutcome.CANCELLED:
  2569. await self.add_reaction(chat_id, message_id, "🚫")
  2570. # ------------------------------------------------------------------ #
  2571. # Asset upload (chunked)
  2572. # ------------------------------------------------------------------ #
  2573. async def _upload_asset(self, room_id: str, file_path: str) -> str | None:
  2574. """Upload a file via the chunked AssetUploadService.
  2575. Returns the asset ID on success, or None on failure.
  2576. """
  2577. try:
  2578. file_data = await asyncio.to_thread(_read_file_bytes, file_path)
  2579. except Exception as e:
  2580. logger.error("Chatto: failed to read file %s — %s", file_path, e)
  2581. return None
  2582. if not file_data:
  2583. logger.error("Chatto: file %s is empty", file_path)
  2584. return None
  2585. file_size = len(file_data)
  2586. file_name = os.path.basename(file_path)
  2587. mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
  2588. sha256_hash = hashlib.sha256(file_data).hexdigest()
  2589. client = await self._get_chatto_client()
  2590. if client is None:
  2591. logger.error("Chatto: upload aborted - no client available")
  2592. return None
  2593. try:
  2594. # Step 1: Create upload session
  2595. upload = await client.create_upload(
  2596. room_id=room_id,
  2597. filename=file_name,
  2598. size=file_size,
  2599. sha256=sha256_hash,
  2600. content_type=mime_type,
  2601. )
  2602. # AssetUpload names this upload_id, not id — reading it through an
  2603. # untyped getattr default is what let the mismatch reach production.
  2604. upload_id = upload.upload_id
  2605. if not upload_id:
  2606. logger.error("Chatto: CreateUpload returned no upload ID")
  2607. return None
  2608. # Step 2: Upload chunks
  2609. offset = 0
  2610. while offset < file_size:
  2611. chunk = file_data[offset : offset + ChattoConstants.UPLOAD_CHUNK_SIZE]
  2612. chunk_sha256 = hashlib.sha256(chunk).hexdigest()
  2613. await client.upload_chunk(
  2614. upload_id=upload_id,
  2615. offset=offset,
  2616. content=chunk,
  2617. chunk_sha256=chunk_sha256,
  2618. )
  2619. offset += len(chunk)
  2620. # Step 3: Complete upload
  2621. upload, asset = await client.complete_upload(upload_id=upload_id)
  2622. if not asset:
  2623. logger.error("Chatto: CompleteUpload returned no asset")
  2624. return None
  2625. logger.info(
  2626. "Chatto: uploaded %s as asset %s (%d bytes)",
  2627. file_name,
  2628. asset.id,
  2629. file_size,
  2630. )
  2631. return asset.id
  2632. except ChattoError as e:
  2633. logger.error("Chatto: upload failed: %s", e)
  2634. return None
  2635. except Exception as e:
  2636. logger.error("Chatto: upload error: %s", e)
  2637. return None
  2638. async def _post_attachment_message(
  2639. self,
  2640. chat_id: str,
  2641. asset_ids: list[str],
  2642. caption: str | None,
  2643. reply_to: str | None,
  2644. metadata: dict[str, Any] | None,
  2645. ) -> SendResult:
  2646. """Post one message carrying already-uploaded assets.
  2647. Threading follows the same rules as a text send
  2648. (:meth:`_resolve_outbound_thread`), so with ``auto_thread`` disabled an
  2649. attachment reply lands in the room like its text counterpart instead of
  2650. quietly opening a thread.
  2651. """
  2652. thread_id = self._resolve_outbound_thread(chat_id, reply_to, metadata)
  2653. client = await self._get_chatto_client()
  2654. if client is None:
  2655. return SendResult(
  2656. success=False, error="Chatto client not available", retryable=True
  2657. )
  2658. try:
  2659. msg = await client.post_message(
  2660. room_id=str(chat_id),
  2661. body=self.format_message(caption) if caption else "",
  2662. attachment_asset_ids=asset_ids,
  2663. thread_root_event_id=thread_id or "",
  2664. )
  2665. self._mark_seen(msg.id)
  2666. return SendResult(success=True, message_id=msg.id)
  2667. except ChattoError as e:
  2668. # Same classification as the chunked text path: server-side
  2669. # failures retry, anything else is ours and must not loop.
  2670. return SendResult(success=False, error=str(e), retryable=True)
  2671. except Exception as e:
  2672. return SendResult(success=False, error=str(e), retryable=False)
  2673. async def _send_local_file_as_attachment(
  2674. self,
  2675. chat_id: str,
  2676. file_path: str,
  2677. caption: str | None,
  2678. reply_to: str | None,
  2679. metadata: dict[str, Any] | None,
  2680. *,
  2681. kind: str,
  2682. ) -> SendResult:
  2683. """Upload a local file and post it as a native Chatto attachment.
  2684. Shared by ``send_image_file``/``send_document``/``send_video``/
  2685. ``send_voice`` — the upload mechanics are identical, only the wording of
  2686. the failure notice differs. On failure we send that notice as text and
  2687. never the host path (it leaks the Hermes home layout).
  2688. """
  2689. notice = f"⚠️ Couldn't deliver the {kind} attachment."
  2690. safe_path = self.validate_media_delivery_path(file_path)
  2691. if not safe_path:
  2692. logger.warning(
  2693. "[%s] send %s: unsafe path %s",
  2694. self.name,
  2695. kind,
  2696. file_path,
  2697. )
  2698. text = f"{caption}\n{notice}" if caption else notice
  2699. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  2700. asset_id = await self._upload_asset(str(chat_id), safe_path)
  2701. if not asset_id:
  2702. logger.warning(
  2703. "[%s] send %s: upload failed for %s",
  2704. self.name,
  2705. kind,
  2706. safe_path,
  2707. )
  2708. text = f"{caption}\n{notice}" if caption else notice
  2709. return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
  2710. return await self._post_attachment_message(
  2711. chat_id,
  2712. [asset_id],
  2713. caption,
  2714. reply_to,
  2715. metadata,
  2716. )
  2717. async def send_image_file(
  2718. self,
  2719. chat_id: str,
  2720. image_path: str,
  2721. caption: str | None = None,
  2722. reply_to: str | None = None,
  2723. metadata: dict[str, Any] | None = None,
  2724. **kwargs,
  2725. ) -> SendResult:
  2726. """Send a local image file via the chunked upload API.
  2727. The parameter is ``image_path``, not ``file_path``: every caller passes
  2728. it by keyword (``gateway/run.py:22354``, ``:22470``, and the base class's
  2729. own ``send_multiple_images`` file:// branch), so a renamed parameter
  2730. makes each of those raise TypeError and silently degrade to a text
  2731. notice.
  2732. BasePlatformAdapter override
  2733. """
  2734. return await self._send_local_file_as_attachment(
  2735. chat_id,
  2736. image_path,
  2737. caption,
  2738. reply_to,
  2739. metadata,
  2740. kind="image",
  2741. )
  2742. async def send_document(
  2743. self,
  2744. chat_id: str,
  2745. file_path: str,
  2746. caption: str | None = None,
  2747. file_name: str | None = None,
  2748. reply_to: str | None = None,
  2749. metadata: dict[str, Any] | None = None,
  2750. **kwargs,
  2751. ) -> SendResult:
  2752. """Send a local file as a native Chatto attachment.
  2753. ``file_name`` exists in the base-class signature and is accepted for
  2754. compatibility, but Chatto takes the recipient-visible filename from
  2755. the upload session (derived from the local path); failures are logged
  2756. and noticed by ``_send_local_file_as_attachment`` itself.
  2757. BasePlatformAdapter override
  2758. """
  2759. return await self._send_local_file_as_attachment(
  2760. chat_id,
  2761. file_path,
  2762. caption,
  2763. reply_to,
  2764. metadata,
  2765. kind="file",
  2766. )
  2767. async def send_video(
  2768. self,
  2769. chat_id: str,
  2770. video_path: str,
  2771. caption: str | None = None,
  2772. reply_to: str | None = None,
  2773. metadata: dict[str, Any] | None = None,
  2774. **kwargs,
  2775. ) -> SendResult:
  2776. """Send a local video as a native Chatto attachment.
  2777. Chatto transcodes and plays it inline.
  2778. BasePlatformAdapter override
  2779. """
  2780. return await self._send_local_file_as_attachment(
  2781. chat_id,
  2782. video_path,
  2783. caption,
  2784. reply_to,
  2785. metadata,
  2786. kind="video",
  2787. )
  2788. async def send_voice(
  2789. self,
  2790. chat_id: str,
  2791. audio_path: str,
  2792. caption: str | None = None,
  2793. reply_to: str | None = None,
  2794. metadata: dict[str, Any] | None = None,
  2795. **kwargs,
  2796. ) -> SendResult:
  2797. """Send a local audio file as a native Chatto attachment.
  2798. Chatto has no dedicated voice-bubble type, so this is an ordinary audio
  2799. attachment — still far better than the base class's text notice.
  2800. BasePlatformAdapter override
  2801. """
  2802. return await self._send_local_file_as_attachment(
  2803. chat_id,
  2804. audio_path,
  2805. caption,
  2806. reply_to,
  2807. metadata,
  2808. kind="audio",
  2809. )
  2810. async def send_image(
  2811. self,
  2812. chat_id: str,
  2813. image_url: str,
  2814. caption: str | None = None,
  2815. reply_to: str | None = None,
  2816. metadata: dict[str, Any] | None = None,
  2817. ) -> SendResult:
  2818. """Send an image to a Chatto room.
  2819. Materialises the URL (size-capped download, like every inbound
  2820. attachment) and uploads it as a native attachment. Falls back to the
  2821. plain URL as a link — Chatto renders link previews — when the URL
  2822. cannot be materialised or the post after a successful upload fails.
  2823. An upload failure needs no fallback on top: the text notice of
  2824. ``_send_local_file_as_attachment`` has already gone out.
  2825. BasePlatformAdapter override
  2826. """
  2827. link_text = f"{caption}\n{image_url}" if caption else image_url
  2828. path, is_temp = await self._materialise_image(image_url)
  2829. if path is not None:
  2830. try:
  2831. result = await self._send_local_file_as_attachment(
  2832. chat_id, path, caption, reply_to, metadata, kind="image"
  2833. )
  2834. finally:
  2835. if is_temp:
  2836. try:
  2837. os.unlink(path)
  2838. except OSError:
  2839. pass
  2840. if result.success:
  2841. return result
  2842. return await self.send(chat_id, link_text, reply_to=reply_to, metadata=metadata)
  2843. async def _materialise_image(self, image_url: str) -> tuple[str | None, bool]:
  2844. """Resolve one ``send_multiple_images`` entry to a local file path.
  2845. Accepts ``http(s)://`` URLs (downloaded to a temp file), ``file://``
  2846. URIs and bare paths. Returns ``(path, is_temp)`` — the caller unlinks
  2847. when ``is_temp``. ``(None, False)`` means the entry is unusable.
  2848. """
  2849. if image_url.startswith(("http://", "https://")):
  2850. ext = os.path.splitext(urlsplit(image_url).path)[1] or ".png"
  2851. tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="chatto_img_")
  2852. os.close(tmp_fd)
  2853. try:
  2854. data = await self._download_attachment_bytes(image_url)
  2855. await asyncio.to_thread(_write_file_bytes, tmp_path, data)
  2856. except Exception as e:
  2857. logger.warning("Chatto: image download failed for %s: %s", image_url, e)
  2858. try:
  2859. os.unlink(tmp_path)
  2860. except OSError:
  2861. pass
  2862. return None, False
  2863. return tmp_path, True
  2864. local = image_url
  2865. if local.startswith("file://"):
  2866. local = unquote(urlsplit(local).path)
  2867. return self.validate_media_delivery_path(local), False
  2868. async def send_multiple_images(
  2869. self,
  2870. chat_id: str,
  2871. images: list[tuple[str, str]],
  2872. metadata: dict[str, Any] | None = None,
  2873. human_delay: float = 0.0,
  2874. ) -> SendResult:
  2875. """Send a batch of images as ONE message with several attachments.
  2876. The base implementation posts each image separately; a Chatto message
  2877. carries a list of attachment assets, so a batch belongs in a single
  2878. message (and a single notification).
  2879. ``human_delay`` is ignored deliberately — there is only one outbound
  2880. call to pace. Entries that can't be fetched are dropped with a warning;
  2881. if nothing survives, we fall back to the base class so the user still
  2882. gets the links.
  2883. BasePlatformAdapter override
  2884. """
  2885. if len(images or []) < 2:
  2886. return await super().send_multiple_images(
  2887. chat_id,
  2888. images,
  2889. metadata=metadata,
  2890. human_delay=human_delay,
  2891. )
  2892. asset_ids: list[str] = []
  2893. captions: list[str] = []
  2894. for image_url, alt_text in images:
  2895. path, is_temp = await self._materialise_image(image_url)
  2896. if not path:
  2897. logger.warning("Chatto: skipping unusable image %s", image_url)
  2898. continue
  2899. try:
  2900. asset_id = await self._upload_asset(str(chat_id), path)
  2901. finally:
  2902. if is_temp:
  2903. try:
  2904. os.unlink(path)
  2905. except OSError:
  2906. pass
  2907. if not asset_id:
  2908. logger.warning("Chatto: upload failed for image %s", image_url)
  2909. continue
  2910. asset_ids.append(asset_id)
  2911. if alt_text:
  2912. captions.append(alt_text)
  2913. if not asset_ids:
  2914. logger.warning(
  2915. "Chatto: no image survived upload, falling back to per-image delivery",
  2916. )
  2917. return await super().send_multiple_images(
  2918. chat_id,
  2919. images,
  2920. metadata=metadata,
  2921. human_delay=human_delay,
  2922. )
  2923. if len(asset_ids) < len(images):
  2924. logger.warning(
  2925. "Chatto: sending %d of %d images — the rest could not be uploaded",
  2926. len(asset_ids),
  2927. len(images),
  2928. )
  2929. return await self._post_attachment_message(
  2930. chat_id,
  2931. asset_ids,
  2932. "\n".join(captions) or None,
  2933. None,
  2934. metadata,
  2935. )
  2936. # ---------------------------------------------------------------------------
  2937. # Cron / out-of-process delivery
  2938. # ---------------------------------------------------------------------------
  2939. async def hermes_standalone_sender_fn(
  2940. pconfig: PlatformConfig,
  2941. chat_id: str,
  2942. message: str,
  2943. *,
  2944. thread_id=None,
  2945. media_files=None,
  2946. force_document=False,
  2947. ) -> SendResult:
  2948. """Deliver a message to Chatto without a running gateway adapter. Do not modify signature.
  2949. Used by cron / scheduled routines that run out-of-process. Creates a
  2950. short-lived chattolib client, posts, and closes. Long messages are
  2951. normalised and split like ``send()`` does, so cron output cannot die on
  2952. the server's per-message limit.
  2953. """
  2954. chatto_config: ChattoConfiguration = ChattoConfiguration(pconfig=pconfig)
  2955. # Create a temporary client for standalone sending — needs a base URL and token.
  2956. has_token = bool(chatto_config.token.value)
  2957. if not chatto_config.base_url.value or not has_token:
  2958. return SendResult(success=False, error="Chatto: base URL or token missing")
  2959. client = ChattoClient(
  2960. base_url=chatto_config.base_url.value, token=chatto_config.token.value
  2961. )
  2962. try:
  2963. kwargs: dict[str, Any] = {}
  2964. if chatto_config.auto_thread.value and thread_id:
  2965. kwargs["thread_root_event_id"] = thread_id
  2966. if media_files and media_files.get("attachment_asset_ids"):
  2967. kwargs["attachment_asset_ids"] = list(media_files["attachment_asset_ids"])
  2968. formatted = _normalise_outbound_text(message)
  2969. chunks = BasePlatformAdapter.truncate_message(
  2970. formatted, ChattoConstants.SPLIT_THRESHOLD
  2971. )
  2972. message_ids: list[str] = []
  2973. try:
  2974. for chunk in chunks:
  2975. posted = await client.post_message(chat_id, chunk, **kwargs)
  2976. message_ids.append(posted.id)
  2977. except Exception as exc:
  2978. if message_ids:
  2979. logger.warning(
  2980. "Chatto standalone: sent %d/%d chunk(s) to %s before failing: %s",
  2981. len(message_ids),
  2982. len(chunks),
  2983. chat_id,
  2984. exc,
  2985. )
  2986. # Same classification as the adapter's send paths: only
  2987. # server-side failures read as retryable.
  2988. return SendResult(
  2989. success=False,
  2990. error=str(exc),
  2991. retryable=isinstance(exc, ChattoError),
  2992. )
  2993. return SendResult(success=True, message_id=message_ids[0])
  2994. finally:
  2995. try:
  2996. await client.close()
  2997. except Exception as exc:
  2998. logger.warning(
  2999. "Chatto standalone: error closing short-lived client (perhaps already closed): %s",
  3000. exc,
  3001. )
  3002. # Resolved Chatto configuration — populated by ``hermes_validate_config`` so
  3003. # plugin tools can access it without re-reading env vars or duplicating
  3004. # ``ChattoConfiguration`` logic.
  3005. #
  3006. # Keyed by the profile the snapshot was validated for, not stored in one slot:
  3007. # Hermes multiplexes several profiles through a single gateway process and runs
  3008. # every profile's own validate_config (run_adapters.py, one _create_adapter per
  3009. # profile), so a single global would be whichever profile validated last — and a
  3010. # routed cron fire or turn for another profile would then send with the wrong
  3011. # profile's bot token. The key is the same home key the platform registry scopes
  3012. # its own entries by, so both agree on what "the serving profile" means.
  3013. _resolved_chatto_configs: dict[str, ChattoConfiguration] = {}
  3014. def _profile_scope_key() -> str:
  3015. """Registry key of the profile being served right now.
  3016. Falls back to a constant when ``hermes_constants`` is unavailable (a bare
  3017. standalone sender process): one profile there, so one key loses nothing.
  3018. """
  3019. try:
  3020. from hermes_constants import hermes_home_key
  3021. return hermes_home_key()
  3022. except Exception:
  3023. logger.debug("Chatto: no profile scope key available", exc_info=True)
  3024. return ""
  3025. # How similar an ``extra`` key must be to a declared config_key before the
  3026. # unknown-key check reads it as a likely typo or renamed field.
  3027. _NEAR_MISS_RATIO = 0.75
  3028. def _warn_on_unknown_extra_keys(config: PlatformConfig) -> None:
  3029. """Warn about ``extra`` keys that look like misspelled config fields.
  3030. A typo'd key silently resolves to the default otherwise — the warning is
  3031. the only thing telling the user their ``require_mention_channles`` never
  3032. reached us. Only near-matches against our declared config_keys are
  3033. flagged (difflib similarity): keys that resemble nothing of ours are
  3034. either placed there by the Hermes gateway itself (the shared-key loop in
  3035. load_gateway_config() bridges reply_in_thread & co. into every platform's
  3036. extra, hardcoded inline upstream — nothing to import) or are deliberate
  3037. pass-throughs, and flagging those would just train users to ignore us.
  3038. Internal markers (``_enabled_explicit``) are skipped outright.
  3039. """
  3040. extra: dict[str, Any] = getattr(config, "extra", None) or {}
  3041. known = [field.config_key for field in ChattoConfiguration.fields()]
  3042. for key in sorted(extra):
  3043. if key.startswith("_") or key in known:
  3044. continue
  3045. best = max(known, key=lambda k: SequenceMatcher(None, key, k).ratio())
  3046. if SequenceMatcher(None, key, best).ratio() >= _NEAR_MISS_RATIO:
  3047. logger.warning(
  3048. "Chatto: 'extra' key '%s' matches no config field — did you mean '%s'?",
  3049. key,
  3050. best,
  3051. )
  3052. def hermes_validate_config(config: PlatformConfig) -> bool:
  3053. """Check whether Chatto Plugin is configured.
  3054. Function name should be the same as register argument name with "hermes_" prefix, so we
  3055. know that it is needed for plugin register(). Do not change signature.
  3056. Takes ``config``. Compare to hermes_is_connected().
  3057. """
  3058. resolved = ChattoConfiguration(pconfig=config)
  3059. _warn_on_unknown_extra_keys(config)
  3060. if len(resolved.allowed_users.value) > 0 and resolved.allow_all_users.value:
  3061. logger.error(
  3062. "Chatto: Conflicting configuration. Either use 'allowed_users' or 'allow_all_users' but not both."
  3063. )
  3064. return False
  3065. require_rooms = set(resolved.require_mention_rooms.value)
  3066. optional_rooms = set(resolved.optional_mention_rooms.value)
  3067. overlap = sorted(require_rooms & optional_rooms)
  3068. if overlap:
  3069. logger.error(
  3070. "Chatto: Conflicting configuration. Room(s) %s are on both "
  3071. "'require_mention_rooms' and 'optional_mention_rooms' — "
  3072. "each room must appear in at most one of them.",
  3073. ", ".join(overlap),
  3074. )
  3075. return False
  3076. # base_url always resolves (it defaults to ChattoHQ), so the only real
  3077. # question is whether a token came in.
  3078. if resolved.token.value is None:
  3079. logger.error("Chatto: CHATTO_TOKEN must be set.")
  3080. return False
  3081. # Publish for the plugin tools only now: a config we just rejected is not
  3082. # one they should send with, and a rejected call must not overwrite a
  3083. # snapshot an earlier, accepted call left behind.
  3084. _resolved_chatto_configs[_profile_scope_key()] = resolved
  3085. return True
  3086. def hermes_check_fn() -> bool:
  3087. """Report whether the vendored chattolib dependency can be imported."""
  3088. try:
  3089. from chattolib import (
  3090. client, # noqa: F401 — vendored dependency probe
  3091. )
  3092. return True
  3093. except ImportError:
  3094. return False
  3095. # ---------------------------------------------------------------------------
  3096. # is_connected probe
  3097. # ---------------------------------------------------------------------------
  3098. def hermes_is_connected(config: PlatformConfig) -> bool:
  3099. """Report whether the Chatto platform is configured and enabled.
  3100. The name is fixed by the register() contract, but despite what it
  3101. suggests this does not open a connection — it validates configuration
  3102. only (see :func:`hermes_validate_config`); the gateway probes real
  3103. connectivity through ``connect()``.
  3104. """
  3105. return bool(hermes_validate_config(config) and config.enabled)
  3106. def hermes_setup_fn() -> None:
  3107. """Interactive setup wizard for Chatto. Is called by and only works in Hermes CLI context.
  3108. Function name should be the same as register argument name with "hermes_" prefix, so we
  3109. know that it is needed for plugin register().
  3110. """
  3111. from hermes_cli.setup import (
  3112. print_success,
  3113. prompt,
  3114. prompt_yes_no,
  3115. save_env_value,
  3116. )
  3117. url = prompt(
  3118. "Chatto server URL (e.g. https://chat.example.com) or leave blank for default ChattoHQ on chat.chatto.run:"
  3119. )
  3120. if url:
  3121. save_env_value(ChattoConfiguration.base_url.env_name, url)
  3122. token = prompt("Chatto bot token (cht_BK_...):", password=True)
  3123. if token:
  3124. save_env_value(ChattoConfiguration.token.env_name, token)
  3125. home = prompt("Home room ID for notifications (or empty):")
  3126. if home:
  3127. save_env_value(ChattoConfiguration.home_channel.env_name, home)
  3128. allow_all = prompt_yes_no("Allow all users to talk? (true/false):")
  3129. if allow_all:
  3130. save_env_value(ChattoConfiguration.allow_all_users.env_name, str(allow_all))
  3131. print_success("\n✓ Chatto configured. Restart the gateway to activate.")
  3132. def hermes_env_enablement_fn() -> dict:
  3133. """Seed PlatformConfig.extra from the CHATTO_* environment variables.
  3134. Returns a dict compatible with the PlatformConfig merge hook, holding
  3135. exactly the values that are actually set via env — never fabricated
  3136. defaults. Called by the platform registry during load_gateway_config(),
  3137. which commits this dict onto the platform's ``extra`` verbatim; seeding a
  3138. value that was not configured would overwrite what the user set in
  3139. config.yaml (e.g. a YAML base_url clobbered by the ChattoHQ default).
  3140. "Nothing set" therefore stays the adapter's business: every ConfigField
  3141. falls back to its declared default (base_url to ChattoHQ) on its own.
  3142. Seed keys are the config.yaml "extra" keys (config_key), NOT the env var
  3143. names — ChattoConfiguration reads extra[config_key]. The special
  3144. 'home_channel' key is extracted by the gateway and becomes a proper
  3145. HomeChannel dataclass on the PlatformConfig; every other key is merged
  3146. into PlatformConfig.extra.
  3147. Function name should be the same as register argument name with "hermes_" prefix, so we
  3148. know that it is needed for plugin register().
  3149. """
  3150. seed: dict[str, Any] = {}
  3151. for config_field in ChattoConfiguration.fields():
  3152. env_value = os.getenv(config_field.env_name)
  3153. if env_value:
  3154. seed[config_field.config_key] = env_value.strip()
  3155. logger.debug("seed: %s", {k: v for k, v in seed.items() if k != "token"})
  3156. return seed
  3157. # ---------------------------------------------------------------------------
  3158. # Plugin registration entry point
  3159. # ---------------------------------------------------------------------------
  3160. # What each capability is called in the startup banner, keyed by the method
  3161. # that implements it. Derived from real overrides rather than hard-coded, so
  3162. # dropping a method drops its claim from the log instead of leaving a lie.
  3163. _CAPABILITY_LABELS = {
  3164. "send": "text",
  3165. "send_image_file": "images",
  3166. "send_multiple_images": "image batches (bundled into one message)",
  3167. "send_video": "video",
  3168. "send_voice": "voice messages",
  3169. "send_document": "documents",
  3170. "add_reaction": "reactions",
  3171. "edit_message": "message editing",
  3172. "delete_message": "message deletion",
  3173. "send_typing": "typing indicators",
  3174. "create_handoff_thread": "threads",
  3175. "create_room": "room creation",
  3176. }
  3177. def _capabilities() -> list[str]:
  3178. """Name the things this adapter genuinely implements itself.
  3179. A capability counts only when ChattoAdapter overrides the base method —
  3180. inheriting BasePlatformAdapter's fallback means the feature is not
  3181. natively supported, and announcing it would mislead.
  3182. """
  3183. found = [
  3184. label
  3185. for name, label in _CAPABILITY_LABELS.items()
  3186. if getattr(ChattoAdapter, name, None)
  3187. is not getattr(BasePlatformAdapter, name, None)
  3188. ]
  3189. if ChattoAdapter.supports_code_blocks:
  3190. found.append("code blocks")
  3191. if ChattoAdapter.supports_status_text:
  3192. found.append("custom status text")
  3193. found.append("presence (refreshed while connected)")
  3194. return found
  3195. # --------------------------------------------------------------------------- #
  3196. # Plugin tools: send DM to a user, or send to a room
  3197. # --------------------------------------------------------------------------- #
  3198. class _ToolRefusal(Exception):
  3199. """A tool step that ends the call with a result for the model.
  3200. The rendered JSON travels on the exception, so every early exit reads the
  3201. same to Hermes and none of them escapes as an unhandled error.
  3202. """
  3203. def __init__(self, result_json: str) -> None:
  3204. super().__init__(result_json)
  3205. self.result_json = result_json
  3206. def _refuse(error: str, **extra: Any) -> _ToolRefusal:
  3207. """Build a refusal result, so every early exit agrees on the shape."""
  3208. return _ToolRefusal(json.dumps({"success": False, "error": error, **extra}))
  3209. @asynccontextmanager
  3210. async def _tool_client(cfg: ChattoConfiguration | None) -> AsyncIterator[ChattoClient]:
  3211. """A short-lived client for one tool call, closed however the call ends.
  3212. Credentials come from the resolved configuration and from nowhere else. A
  3213. tool argument carrying ``base_url`` would send the configured bot token to
  3214. whatever host the caller named, and every message the bot reads is
  3215. something a caller could talk it into repeating.
  3216. """
  3217. if cfg is None:
  3218. raise _refuse("Chatto configuration unavailable")
  3219. token = cfg.token.value or ""
  3220. if not token:
  3221. raise _refuse("Chatto token not configured")
  3222. try:
  3223. client = ChattoClient(
  3224. base_url=cfg.base_url.value or ChattoClient.DEFAULT_BASE_URL, token=token
  3225. )
  3226. except Exception as exc:
  3227. raise _refuse(f"Failed to create Chatto client: {exc}") from exc
  3228. try:
  3229. yield client
  3230. finally:
  3231. try:
  3232. await client.close()
  3233. except Exception as exc: # pragma: no cover — close is best-effort
  3234. logger.debug("Chatto tools: client close failed: %s", exc)
  3235. CHATTO_LIST_ROOMS_SCHEMA = {
  3236. "name": "chatto_list_rooms",
  3237. "description": (
  3238. "List the Chatto rooms visible to the bot (channels and DM rooms), with "
  3239. "their room IDs and whether the bot is a member. Check `is_member` before "
  3240. "posting: the bot can see rooms it has not joined, and cannot post in "
  3241. "them. Use this to resolve a channel name to its room ID — e.g. to find "
  3242. "the 'platform:chat_id' address for a cron job's `deliver` target. "
  3243. "Optional `name` filters case-insensitively by substring."
  3244. ),
  3245. "parameters": {
  3246. "type": "object",
  3247. "properties": {
  3248. "name": {
  3249. "type": "string",
  3250. "description": (
  3251. "Optional: case-insensitive substring filter on the room name "
  3252. "(e.g. 'liv' matches 'Liv' and 'Liv-Dev'). Empty lists all rooms."
  3253. ),
  3254. },
  3255. },
  3256. "required": [],
  3257. "additionalProperties": False,
  3258. },
  3259. }
  3260. CHATTO_SEND_DM_SCHEMA = {
  3261. "name": "chatto_send_dm",
  3262. "description": (
  3263. "Send a text message as a **Direct Message** to another Chatto user. "
  3264. "Looks up the user by `user_login` or `user_id` and posts into the DM "
  3265. "room you already have with them. Returns success with the room_id "
  3266. "and message_ids, or an error."
  3267. ),
  3268. "parameters": {
  3269. "type": "object",
  3270. "properties": {
  3271. "user_login": {
  3272. "type": "string",
  3273. "description": (
  3274. "The Chatto login name of the recipient "
  3275. "(e.g. 'nickk'). Exactly one of `user_login` or `user_id` is required."
  3276. ),
  3277. },
  3278. "user_id": {
  3279. "type": "string",
  3280. "description": (
  3281. "The Chatto user ID of the recipient "
  3282. "(e.g. 'Uxxxxxxxx'). Exactly one of `user_login` or `user_id` is required."
  3283. ),
  3284. },
  3285. "message": {
  3286. "type": "string",
  3287. "description": "The message text to send (markdown supported).",
  3288. },
  3289. },
  3290. "required": ["message"],
  3291. "additionalProperties": False,
  3292. },
  3293. }
  3294. CHATTO_SEND_ROOM_SCHEMA = {
  3295. "name": "chatto_send_room",
  3296. "description": (
  3297. "Send a text message to a Chatto **room** (channel or DM room) "
  3298. "by its room ID or room name. Channels the bot is configured to "
  3299. "answer in only — a room on neither mention list stays read-only. "
  3300. "Returns success with the message_ids, or an error."
  3301. ),
  3302. "parameters": {
  3303. "type": "object",
  3304. "properties": {
  3305. "room_id": {
  3306. "type": "string",
  3307. "description": (
  3308. "The Chatto room ID of the destination "
  3309. "(e.g. 'RbmwiHk4vs9a3Ql'). Exactly one of `room_id` or `room_name` is required."
  3310. ),
  3311. },
  3312. "room_name": {
  3313. "type": "string",
  3314. "description": (
  3315. "The display name of the room (case-insensitive). Exactly one "
  3316. "of `room_id` or `room_name` is required. If several rooms "
  3317. "share the name, the call returns their IDs instead of guessing."
  3318. ),
  3319. },
  3320. "message": {
  3321. "type": "string",
  3322. "description": "The message text to send (markdown supported).",
  3323. },
  3324. "thread_root_event_id": {
  3325. "type": "string",
  3326. "description": (
  3327. "Optional: event ID of the thread-root message. When given, "
  3328. "this message is posted INSIDE that thread, which has to be "
  3329. "a thread root of the destination room. Mutually exclusive "
  3330. "with `create_thread`."
  3331. ),
  3332. },
  3333. "create_thread": {
  3334. "type": "boolean",
  3335. "description": (
  3336. "Optional: post this message as the ROOT of a new thread "
  3337. "(default false = normal message). Only for channel rooms. "
  3338. "Mutually exclusive with `thread_root_event_id`."
  3339. ),
  3340. },
  3341. },
  3342. "required": ["message"],
  3343. "additionalProperties": False,
  3344. },
  3345. }
  3346. def _chatto_config_for_tools() -> ChattoConfiguration | None:
  3347. """Resolve the Chatto configuration for plugin tool handlers.
  3348. Two tiers, most specific first:
  3349. 1. The snapshot ``hermes_validate_config`` published for *this* profile — the
  3350. authoritative one in a running gateway.
  3351. 2. A fresh read of config.yaml plus the serving profile's own secrets, for
  3352. the cron and standalone sessions where the gateway load hooks never ran
  3353. and the dotenv residue has been stripped from ``os.environ``. Mirrors how
  3354. the built-in send_message tool resolves its pconfig
  3355. (tools/send_message_tool.py).
  3356. Both tiers are keyed by the serving profile, so a multiplexed gateway hands
  3357. each profile its own credentials rather than whichever one was served last.
  3358. Returns ``None`` when neither tier yields a configuration; the caller
  3359. reports that rather than guessing at credentials.
  3360. """
  3361. scope_key = _profile_scope_key()
  3362. snapshot = _resolved_chatto_configs.get(scope_key)
  3363. if snapshot is not None:
  3364. return snapshot
  3365. # config.yaml's own ``extra`` block, so a deployment configured there — and
  3366. # nowhere in .env — is honoured outside the gateway process too.
  3367. try:
  3368. from gateway.config import Platform as GatewayPlatform
  3369. from gateway.config import load_gateway_config
  3370. pconfig = load_gateway_config().platforms.get(
  3371. GatewayPlatform(ChattoConstants.PLATFORM_NAME)
  3372. )
  3373. resolved = ChattoConfiguration(pconfig=_pconfig_or_empty(pconfig))
  3374. except Exception as exc:
  3375. logger.warning("Chatto tools: could not read gateway config: %s", exc)
  3376. return None
  3377. # In a fresh cron scope the dotenv residue is stripped from os.environ, so
  3378. # ChattoConfiguration's env layer sees nothing. The secrets then come from
  3379. # the scope Hermes installed for the profile being served when there is one —
  3380. # that mapping is that profile's authoritative secret set, and rebuilding
  3381. # one from the launch home would answer with another profile's credentials.
  3382. # With no scope installed (CLI, bare standalone sender) the profile's own
  3383. # .env is the right source, and build_profile_secret_scope reads it
  3384. # directly in gateway, cron and CLI contexts alike.
  3385. try:
  3386. from agent.secret_scope import current_secret_scope
  3387. profile_secrets = current_secret_scope()
  3388. if profile_secrets is None:
  3389. from agent.secret_scope import build_profile_secret_scope
  3390. from hermes_constants import get_hermes_home
  3391. profile_secrets = dict(build_profile_secret_scope(get_hermes_home()))
  3392. except Exception as exc:
  3393. logger.warning("Chatto tools: profile secret scope build failed: %s", exc)
  3394. profile_secrets = {}
  3395. resolved.overlay_profile_secrets(profile_secrets)
  3396. # Cache only a configuration that can actually send. Caching a tokenless one
  3397. # would pin this failure for the life of the process: the next call in a
  3398. # properly scoped context would be served the degraded config and keep
  3399. # reporting "token not configured" long after the scope came back.
  3400. if resolved.token.value:
  3401. _resolved_chatto_configs[scope_key] = resolved
  3402. return resolved
  3403. def _room_answers_in(
  3404. cfg: ChattoConfiguration | None, room_id: str, kind: RoomKind | None
  3405. ) -> bool:
  3406. """Whether the bot takes part in this room: answers there, and may post.
  3407. The single definition of that question, on purpose. It answers for two
  3408. callers whose disagreement would be a bug the user cannot see:
  3409. - ``ChattoAdapter._answers_in_room``, the *inbound* gate — whether a
  3410. message here reaches the agent at all
  3411. - ``_room_is_writable``, the *outbound* gate on the send tools, so a tool
  3412. cannot post into a room that would never have answered
  3413. Chatto knows only DMs and channels, so the split is ``kind == DM``: a DM
  3414. always answers (``/join`` must stay reachable), and every other kind —
  3415. channel, an unknown kind (which is how servers that never set ``kind`` show
  3416. up), or a room the adapter has not resolved yet, so ``kind`` is None —
  3417. opts in through one of the two mention lists. The lists are mutually
  3418. exclusive by validation; should contradictory config reach a running adapter
  3419. anyway, optional beats require, because answering a room is safer than
  3420. muting it. A ``cfg`` of None means no configuration could be resolved at
  3421. all, and then nothing but a DM qualifies.
  3422. """
  3423. if kind == RoomKind.DM:
  3424. return True
  3425. if cfg is None:
  3426. return False
  3427. if room_id in cfg.optional_mention_rooms.value:
  3428. return True
  3429. return room_id in cfg.require_mention_rooms.value
  3430. def _pconfig_or_empty(pconfig: PlatformConfig | None) -> PlatformConfig:
  3431. """The Chatto PlatformConfig from config.yaml, or an empty stand-in."""
  3432. if pconfig is not None:
  3433. return pconfig
  3434. from gateway.config import PlatformConfig as GatewayPlatformConfig
  3435. return GatewayPlatformConfig(enabled=True, extra={})
  3436. def _room_is_writable(
  3437. cfg: ChattoConfiguration | None, room: Room, room_id: str
  3438. ) -> bool:
  3439. """Whether the bot may post into this room on its own initiative.
  3440. Delegates to ``_room_answers_in`` so the outbound gate is the *same*
  3441. function as the inbound one: a room that would never be answered must not
  3442. be postable, and two copies of that rule would drift apart until the send
  3443. tool became a way around the read-only promise.
  3444. """
  3445. return _room_answers_in(cfg, room_id, room.kind)
  3446. def _not_joined_refusal(room: Room) -> _ToolRefusal:
  3447. """The refusal for a room the bot can see but has not joined.
  3448. The two room kinds need different advice, and giving a channel the DM
  3449. remedy sends the user down a path that cannot work: a direct message to the
  3450. bot is not how you get it into a channel. For a channel the paths are an
  3451. invite in Chatto, or the ``/join`` the bot answers over DM.
  3452. """
  3453. remedy = (
  3454. f"Invite the bot account in Chatto, or DM it `/join {room.id}`"
  3455. if room.kind == RoomKind.CHANNEL
  3456. else "Have someone start a DM with the bot account"
  3457. )
  3458. return _refuse(
  3459. f"Room '{room.name or room.id}' ({room.id}) is not one the bot has "
  3460. f"joined, so it cannot post there. {remedy}, then try again."
  3461. )
  3462. def _read_only_room_refusal(room_label: str) -> _ToolRefusal:
  3463. """The refusal a read-only room earns, naming where to opt it in.
  3464. This reply is where an operator copies the room ID from, so it spells both
  3465. env vars out verbatim.
  3466. """
  3467. return _refuse(
  3468. f"Room '{room_label}' is configured read-only: the bot neither answers "
  3469. "there nor posts to it on its own initiative. To allow that, add the "
  3470. f"room ID to {ChattoConfiguration.require_mention_rooms.env_name} (only "
  3471. f"answers when addressed) or {ChattoConfiguration.optional_mention_rooms.env_name} "
  3472. "(answers everything) in ~/.hermes/.env, and restart the gateway."
  3473. )
  3474. class _ChunkDelivery(NamedTuple):
  3475. """What a split send actually put into a room.
  3476. ``error`` is the exception that stopped the batch, if any: the chunks in
  3477. ``message_ids`` did go out and must not be resent. Each caller shapes this
  3478. into its own result contract — a ``SendResult`` for the adapter, a refusal
  3479. for the tools — because those are genuinely different contracts; the
  3480. *sending* is not. ``chunks_total`` counts what the split produced, so a
  3481. caller can report "got 1 of 3 out" without re-deriving the split.
  3482. """
  3483. message_ids: list[str]
  3484. root_event_id: str
  3485. error: Exception | None
  3486. chunks_total: int
  3487. async def _deliver_chunks(
  3488. client: ChattoClient,
  3489. room_id: str,
  3490. message: str,
  3491. *,
  3492. thread_root_event_id: str = "",
  3493. create_thread: bool = False,
  3494. on_posted: Callable[[str], None] | None = None,
  3495. ) -> _ChunkDelivery:
  3496. """Post a message split at the server limit, stopping at the first failure.
  3497. One implementation for both send paths, because the decisions are the same
  3498. and a copy of each drifts: split at ``SPLIT_THRESHOLD`` like every other
  3499. send, and route a split answer as *one* answer — chunk 1 opens a thread
  3500. (``create_thread``) or joins the one passed in, and every later chunk
  3501. carries that root, so a long reply does not scatter across the timeline.
  3502. ``on_posted`` is the adapter's ``_mark_seen``: the tools have no dedup state
  3503. to keep, the adapter must not treat its own output as unread input. The
  3504. first failure stops the batch and is returned rather than raised — the
  3505. caller knows better than this function what a partial send means to it, and
  3506. what to call the exception (``ChattoError`` is a server failure, anything
  3507. else is a bug here).
  3508. """
  3509. normalised = _normalise_outbound_text(message)
  3510. chunks = BasePlatformAdapter.truncate_message(
  3511. normalised, ChattoConstants.SPLIT_THRESHOLD
  3512. )
  3513. message_ids: list[str] = []
  3514. root_id = thread_root_event_id
  3515. for chunk in chunks:
  3516. try:
  3517. posted = await client.post_message(
  3518. room_id=room_id, body=chunk, thread_root_event_id=root_id
  3519. )
  3520. except Exception as exc:
  3521. return _ChunkDelivery(message_ids, root_id, exc, len(chunks))
  3522. message_ids.append(posted.id)
  3523. if on_posted is not None:
  3524. on_posted(posted.id)
  3525. if create_thread and not root_id:
  3526. root_id = posted.id
  3527. return _ChunkDelivery(message_ids, root_id, None, len(chunks))
  3528. async def _post_chunks(
  3529. client: ChattoClient,
  3530. room_id: str,
  3531. message: str,
  3532. *,
  3533. thread_root_event_id: str = "",
  3534. create_thread: bool = False,
  3535. ) -> tuple[list[str], str]:
  3536. """Post a message through ``_deliver_chunks`` as a tool result. ``(ids, root)``.
  3537. A chunk that fails leaves the earlier ones delivered, so this refuses with
  3538. exactly what went out: calling a half-delivered send a plain failure
  3539. invites an agent to retry and duplicate what the room already has.
  3540. """
  3541. delivery = await _deliver_chunks(
  3542. client,
  3543. room_id,
  3544. message,
  3545. thread_root_event_id=thread_root_event_id,
  3546. create_thread=create_thread,
  3547. )
  3548. if delivery.error is not None:
  3549. # Blame the server only for a server error. chattolib maps every
  3550. # transport failure to ChattoError, so anything else is a bug on our
  3551. # side — calling that "Chatto API error" would send an operator hunting
  3552. # the wrong component.
  3553. cause = (
  3554. "Chatto API error"
  3555. if isinstance(delivery.error, ChattoError)
  3556. else "Internal plugin error"
  3557. )
  3558. raise _refuse(
  3559. f"{cause} on chunk {len(delivery.message_ids) + 1}/"
  3560. f"{delivery.chunks_total}: {delivery.error}",
  3561. # partial marks a half-delivered send; the caller must not
  3562. # resend it from the top without knowing about these chunks.
  3563. partial=bool(delivery.message_ids),
  3564. room_id=room_id,
  3565. message_ids=delivery.message_ids,
  3566. chunks_sent=len(delivery.message_ids),
  3567. chunks_total=delivery.chunks_total,
  3568. ) from delivery.error
  3569. return delivery.message_ids, delivery.root_event_id
  3570. async def _find_user_by_login(client: ChattoClient, user_login: str) -> tuple[str, str]:
  3571. """Find a user among the members of our DM rooms, ``(user_id, login)``.
  3572. Both are empty when no room yields the login. Only a person can start a DM,
  3573. so a DM room is the only place a deliverable recipient can be — scanning
  3574. the channels the bot sits in would cost one member RPC per room and could
  3575. resolve a login whose DM does not exist yet. A bot cannot read the
  3576. server-wide user directory either: that needs admin rights.
  3577. Every DM room is searched, including one whose membership the directory
  3578. left unreported — that field is optional, and skipping such a room would
  3579. make its login unfindable while the DM room sits right there.
  3580. """
  3581. for rws in await client.list_rooms():
  3582. room = rws.room
  3583. if room is None or room.kind != RoomKind.DM:
  3584. continue
  3585. try:
  3586. member_ids, _ = await client.list_room_members(room.id, search=user_login)
  3587. except ChattoError as exc:
  3588. # A room we cannot enumerate must not abort the search over the
  3589. # remaining ones.
  3590. logger.debug("Chatto tools: member search in %s failed: %s", room.id, exc)
  3591. continue
  3592. if not member_ids:
  3593. continue
  3594. for member in await client.batch_get_room_members(room.id, member_ids):
  3595. user = member.user
  3596. if (
  3597. user is not None
  3598. and user.login
  3599. and user.login.casefold() == user_login.casefold()
  3600. ):
  3601. return user.id, user.login
  3602. return "", ""
  3603. async def _find_dm_room(
  3604. client: ChattoClient, our_id: str, other_id: str
  3605. ) -> Room | None:
  3606. """The DM room between two users, or None when there is none yet.
  3607. Membership is read from the room object the directory already returned, and
  3608. only falls back to a ListMembers RPC when that came back empty:
  3609. ``member_user_ids`` is not among the fields the ListRooms documentation
  3610. lists for ``RoomWithViewerState``, so a server is free to leave it
  3611. unpopulated — and a DM room we can see plainly exists, whatever the
  3612. directory said about who is in it. The fallback costs one RPC per DM room
  3613. and only on servers that need it.
  3614. """
  3615. for rws in await client.list_rooms():
  3616. room = rws.room
  3617. if room is None or room.kind != RoomKind.DM:
  3618. continue
  3619. if rws.member_user_ids:
  3620. if other_id in rws.member_user_ids and our_id in rws.member_user_ids:
  3621. return room
  3622. continue
  3623. try:
  3624. member_ids, _page = await client.list_room_members(room.id)
  3625. except ChattoError as exc:
  3626. # An unreadable room cannot be the one we want, but it must not
  3627. # abort the search over the remaining ones.
  3628. logger.debug("Chatto tools: members of DM %s unreadable: %s", room.id, exc)
  3629. continue
  3630. if other_id in member_ids and our_id in member_ids:
  3631. return room
  3632. return None
  3633. class _ResolvedRoom(NamedTuple):
  3634. """A room the send path resolved, plus whether the bot belongs to it.
  3635. Membership travels with the room because the directory answers a broader
  3636. question than the send path can use: a room the bot can *see* is not one it
  3637. can *post in* (ListRooms returns visible channels, membership or room.list
  3638. permission). Splitting that into two lookups would be a second chance to
  3639. disagree with the state the first one already carried.
  3640. """
  3641. room: Room
  3642. is_member: bool
  3643. async def _resolve_room(
  3644. client: ChattoClient, room_id: str, room_name: str
  3645. ) -> _ResolvedRoom:
  3646. """The destination room, by ID or by name.
  3647. A name is not unique on Chatto — two room groups may both hold an "Ops" —
  3648. and delivering to whichever the directory listed first is not a choice
  3649. anyone made, so an ambiguous name asks for the ID instead.
  3650. """
  3651. if room_id:
  3652. room_viewer_state = await client.get_room(room_id)
  3653. if room_viewer_state is None or room_viewer_state.room is None:
  3654. raise _refuse(
  3655. f"Room {room_id} was not found, or the bot cannot see it. "
  3656. "Use chatto_list_rooms to look up a room ID."
  3657. )
  3658. return _ResolvedRoom(
  3659. room_viewer_state.room, room_viewer_state.viewer_state.is_member
  3660. )
  3661. matches = [
  3662. _ResolvedRoom(rws.room, rws.viewer_state.is_member)
  3663. for rws in await client.list_rooms()
  3664. if rws.room is not None
  3665. and (rws.room.name or "").casefold() == room_name.casefold()
  3666. ]
  3667. if not matches:
  3668. raise _refuse(
  3669. f"Room not found: {room_name}. Use chatto_list_rooms to see the available names."
  3670. )
  3671. if len(matches) > 1:
  3672. candidates = ", ".join(
  3673. f"{match.room.id} ('{match.room.name}')" for match in matches
  3674. )
  3675. raise _refuse(
  3676. f"Room name '{room_name}' is ambiguous — {len(matches)} rooms carry it: "
  3677. f"{candidates}. Pass the room_id instead."
  3678. )
  3679. return matches[0]
  3680. async def _send_dm(args: dict) -> str:
  3681. """Resolve the recipient, find the DM room, post. See _handle_chatto_send_dm."""
  3682. user_login = args.get("user_login") or ""
  3683. user_id = args.get("user_id") or ""
  3684. message = args.get("message") or ""
  3685. if not message:
  3686. raise _refuse("message is required")
  3687. if not user_login and not user_id:
  3688. raise _refuse("Exactly one of user_login or user_id is required")
  3689. async with _tool_client(_chatto_config_for_tools()) as client:
  3690. # A bot cannot read the server-wide user directory (that needs admin
  3691. # rights), so a login is resolved among the members of shared rooms.
  3692. target_user_id = user_id
  3693. target_login = user_login
  3694. if not target_user_id:
  3695. target_user_id, target_login = await _find_user_by_login(client, user_login)
  3696. if not target_user_id:
  3697. raise _refuse(f"User not found: {user_login} shares no DM with the bot")
  3698. # Only people may start a DM (Chatto permissions guide), so a recipient
  3699. # who has never written to the bot has no room to post into — say so
  3700. # instead of guessing at a server rejection later.
  3701. dm_room = await _find_dm_room(client, (await client.me()).id, target_user_id)
  3702. if dm_room is None:
  3703. raise _refuse(
  3704. f"No DM with {user_login or user_id} exists yet: on Chatto only a "
  3705. "person can start a DM, so they have to send the bot a message "
  3706. "once before it can message them"
  3707. )
  3708. message_ids, _root_id = await _post_chunks(client, dm_room.id, message)
  3709. return json.dumps(
  3710. {
  3711. "success": True,
  3712. "dm_room_id": dm_room.id,
  3713. "recipient": target_login,
  3714. "recipient_user_id": target_user_id,
  3715. "message_ids": message_ids,
  3716. "chunks_sent": len(message_ids),
  3717. }
  3718. )
  3719. async def _send_room(args: dict) -> str:
  3720. """Resolve the room, check the gates, post. See _handle_chatto_send_room."""
  3721. room_id = args.get("room_id") or ""
  3722. room_name = args.get("room_name") or ""
  3723. message = args.get("message") or ""
  3724. thread_root_event_id = args.get("thread_root_event_id") or ""
  3725. create_thread = bool(args.get("create_thread", False))
  3726. if not message:
  3727. raise _refuse("message is required")
  3728. if not room_id and not room_name:
  3729. raise _refuse("Exactly one of room_id or room_name is required")
  3730. if thread_root_event_id and create_thread:
  3731. raise _refuse("thread_root_event_id and create_thread are mutually exclusive")
  3732. cfg = _chatto_config_for_tools()
  3733. async with _tool_client(cfg) as client:
  3734. resolved = await _resolve_room(client, room_id, room_name)
  3735. room = resolved.room
  3736. # Posting into a room the plugin treats as read-only would break a
  3737. # promise the README makes about unlisted rooms staying silent.
  3738. if not _room_is_writable(cfg, room, room.id):
  3739. raise _read_only_room_refusal(room.name or room.id)
  3740. if create_thread and room.kind == RoomKind.DM:
  3741. raise _refuse(
  3742. "A DM has no threads: drop create_thread and send it as a normal message."
  3743. )
  3744. # The directory lists rooms the bot can see but has not joined, and
  3745. # posting into one fails server-side with an error that names neither
  3746. # the room nor the fix.
  3747. if not resolved.is_member:
  3748. raise _not_joined_refusal(room)
  3749. # A thread root has to belong to the room we post into, or the message
  3750. # attaches to a thread somewhere else entirely. And it has to BE a root:
  3751. # passing a reply's ID would attach to a thread nobody can follow.
  3752. if thread_root_event_id:
  3753. root = await client.get_message(room.id, thread_root_event_id)
  3754. if root is None:
  3755. raise _refuse(
  3756. f"No message {thread_root_event_id} in room {room.id}. "
  3757. "Send without thread_root_event_id to post to the room itself."
  3758. )
  3759. if root.thread_root_event_id:
  3760. raise _refuse(
  3761. f"Message {thread_root_event_id} is a reply inside thread "
  3762. f"{root.thread_root_event_id}, not a thread root. Pass that "
  3763. "thread's root ID, or send without thread_root_event_id."
  3764. )
  3765. message_ids, root_event_id = await _post_chunks(
  3766. client,
  3767. room.id,
  3768. message,
  3769. thread_root_event_id=thread_root_event_id,
  3770. create_thread=create_thread,
  3771. )
  3772. # Any thread the bot posts into is followed, not only one it opened:
  3773. # Chatto delivers a thread's replies to an account that follows it (or
  3774. # was mentioned in it directly), so replying into someone else's thread
  3775. # without following it can end the conversation the agent just joined.
  3776. # Mirrors the adapter's own send(), which follows every thread it uses.
  3777. if root_event_id:
  3778. try:
  3779. await client.follow_thread(room.id, root_event_id)
  3780. except Exception as exc:
  3781. # Follow is best-effort: the thread exists and the message was
  3782. # delivered, so a hiccup here is not a failed send.
  3783. logger.debug(
  3784. "Chatto tools: follow_thread(%s) failed: %s", root_event_id, exc
  3785. )
  3786. return json.dumps(
  3787. {
  3788. "success": True,
  3789. "room_id": room.id,
  3790. "room_name": room.name,
  3791. "message_ids": message_ids,
  3792. "chunks_sent": len(message_ids),
  3793. "thread_root_event_id": root_event_id,
  3794. "created_thread": bool(create_thread),
  3795. }
  3796. )
  3797. async def _list_rooms(args: dict) -> str:
  3798. """List the rooms visible to the bot. See _handle_chatto_list_rooms."""
  3799. name_filter = (args.get("name") or "").strip().casefold()
  3800. async with _tool_client(_chatto_config_for_tools()) as client:
  3801. rooms_out = []
  3802. for rws in await client.list_rooms():
  3803. room = rws.room
  3804. if room is None:
  3805. continue
  3806. # A filter implies named rooms: skip DMs (empty name) and
  3807. # non-matching names alike.
  3808. if name_filter and not (room.name and name_filter in room.name.casefold()):
  3809. continue
  3810. rooms_out.append(
  3811. {
  3812. "room_id": room.id,
  3813. "name": room.name or "",
  3814. "kind": room.kind.value,
  3815. "threading_mode": room.threading_mode.value,
  3816. "archived": room.archived,
  3817. "is_member": rws.viewer_state.is_member,
  3818. # DM rooms carry no name, so they are labelled by their ID
  3819. # instead of leaving the model with a blank to match on.
  3820. "label": room.name or f"(DM room {room.id})",
  3821. }
  3822. )
  3823. return json.dumps(
  3824. {
  3825. "success": True,
  3826. "count": len(rooms_out),
  3827. "rooms": rooms_out,
  3828. "hint": (
  3829. "Use room_id in chatto_send_room, or as the chat_id part of a "
  3830. "cron deliver target like 'chatto-platform:<room_id>'."
  3831. ),
  3832. }
  3833. )
  3834. async def _handle_chatto_send_dm(args: dict) -> str:
  3835. """Tool handler for chatto_send_dm.
  3836. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  3837. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  3838. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  3839. refusal's own JSON, so no path escapes as an unhandled error.
  3840. """
  3841. try:
  3842. return await _send_dm(args)
  3843. except _ToolRefusal as refusal:
  3844. return refusal.result_json
  3845. except ChattoAuthError as exc:
  3846. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  3847. except ChattoError as exc:
  3848. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  3849. async def _handle_chatto_send_room(args: dict) -> str:
  3850. """Tool handler for chatto_send_room.
  3851. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  3852. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  3853. type". Every early exit arrives here as a _ToolRefusal and leaves as that
  3854. refusal's own JSON, so no path escapes as an unhandled error.
  3855. """
  3856. try:
  3857. return await _send_room(args)
  3858. except _ToolRefusal as refusal:
  3859. return refusal.result_json
  3860. except ChattoAuthError as exc:
  3861. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  3862. except ChattoError as exc:
  3863. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  3864. async def _handle_chatto_list_rooms(args: dict) -> str:
  3865. """Tool handler for chatto_list_rooms.
  3866. Returns a JSON string: Hermes' tool contract accepts no other type, and a
  3867. dict (or an unflagged coroutine) fails at dispatch with "unsupported result
  3868. type".
  3869. """
  3870. try:
  3871. return await _list_rooms(args)
  3872. except _ToolRefusal as refusal:
  3873. return refusal.result_json
  3874. except ChattoAuthError as exc:
  3875. return json.dumps({"success": False, "error": f"Authentication error: {exc}"})
  3876. except ChattoError as exc:
  3877. return json.dumps({"success": False, "error": f"Chatto API error: {exc}"})
  3878. def _register_bundled_skills(ctx) -> None:
  3879. """Register the skills shipped in ``skills/``, each with its own description.
  3880. ``register_skill`` stores the description verbatim and never reads the
  3881. SKILL.md frontmatter, so passing none leaves the skill listed in
  3882. ``<available_skills>`` with nothing explaining when to load it — which is
  3883. the only place an agent learns it exists.
  3884. """
  3885. from pathlib import Path
  3886. from agent.skill_utils import parse_frontmatter
  3887. skills_dir = Path(__file__).parent / "skills"
  3888. if not skills_dir.is_dir():
  3889. logger.debug("Chatto: no bundled skills directory at %s", skills_dir)
  3890. return
  3891. for child in sorted(skills_dir.iterdir()):
  3892. skill_md = child / "SKILL.md"
  3893. if not (child.is_dir() and skill_md.exists()):
  3894. continue
  3895. frontmatter, _ = parse_frontmatter(skill_md.read_text(encoding="utf-8"))
  3896. ctx.register_skill(
  3897. child.name,
  3898. str(skill_md),
  3899. description=str(frontmatter.get("description") or ""),
  3900. frontmatter=frontmatter,
  3901. )
  3902. logger.info("Chatto plugin skill registered: %s", child.name)
  3903. # The plugin's outbound tools: (tool name, JSON schema, handler). One list, so
  3904. # the two registration entry points below cannot disagree about what exists.
  3905. _PLUGIN_TOOLS = (
  3906. ("chatto_send_dm", CHATTO_SEND_DM_SCHEMA, _handle_chatto_send_dm),
  3907. ("chatto_send_room", CHATTO_SEND_ROOM_SCHEMA, _handle_chatto_send_room),
  3908. ("chatto_list_rooms", CHATTO_LIST_ROOMS_SCHEMA, _handle_chatto_list_rooms),
  3909. )
  3910. def register_plugin_tools(ctx) -> None:
  3911. """Register the plugin's outbound tools in the ``chatto-platform`` toolset.
  3912. Reached through two doors: ``register()`` in a gateway/web process, which
  3913. materializes the platform, and ``tools.register_tools`` in a CLI/TUI one,
  3914. which never does. A tool list written out twice would mean tools that exist
  3915. in only half the sessions, so both doors call this.
  3916. """
  3917. for name, schema, handler in _PLUGIN_TOOLS:
  3918. ctx.register_tool(
  3919. name=name,
  3920. toolset="chatto-platform",
  3921. schema=schema,
  3922. handler=handler,
  3923. is_async=True,
  3924. description=schema["description"],
  3925. )
  3926. def register(ctx) -> None:
  3927. """Plugin entry point — called by the Hermes plugin system."""
  3928. logger.info("Registering Chatto platform plugin on Hermes Agent")
  3929. # --- Plugin tools ---
  3930. register_plugin_tools(ctx)
  3931. # --- Bundled skills ---
  3932. # Ship the plugin's own usage/development knowledge with the code, so any
  3933. # agent using this plugin knows when/how to use its tools and how to
  3934. # extend it. Loaded via skill_view("chatto-platform:chatto-platform-plugin").
  3935. _register_bundled_skills(ctx)
  3936. for capability in _capabilities():
  3937. logger.info("Chatto capability: %s", capability)
  3938. ctx.register_platform(
  3939. name=ChattoConstants.PLATFORM_NAME, # this will be the config.yaml key.
  3940. label=ChattoConstants.PLATFORM_LABEL,
  3941. adapter_factory=hermes_adapter_factory,
  3942. check_fn=hermes_check_fn,
  3943. validate_config=hermes_validate_config,
  3944. is_connected=hermes_is_connected,
  3945. install_hint=ChattoConstants.INSTALL_HINT,
  3946. env_enablement_fn=hermes_env_enablement_fn,
  3947. setup_fn=hermes_setup_fn,
  3948. cron_deliver_env_var=ChattoConfiguration.home_channel.env_name,
  3949. standalone_sender_fn=hermes_standalone_sender_fn,
  3950. allowed_users_env=ChattoConfiguration.allowed_users.env_name,
  3951. allow_all_env=ChattoConfiguration.allow_all_users.env_name,
  3952. max_message_length=ChattoConstants.MAX_MESSAGE_LENGTH,
  3953. emoji="😺",
  3954. allow_update_command=True,
  3955. pii_safe=False,
  3956. platform_hint=(
  3957. "Using the 'Hermes Chatto Platform Plugin' you connect to a Chatto server. "
  3958. "Authorized admins and users will contact you and call you his Hermes Agent. They are "
  3959. "natural persons and thus responsible for what they do in terms of rights. You compute "
  3960. "on their behalf. They _may_ address you by @-mentioning your name. If configured, "
  3961. "you also react without a @-mention. Direct messages reach you without a mention."
  3962. "Keep responses conversational. Markdown is supported. "
  3963. "Include MEDIA:/absolute/path/to/file in your response to refer to our local files. Images "
  3964. "(.png, .jpg, .gif, .webp) arrive as inline pictures, videos (.mp4, .mov, .webm) as "
  3965. "video attachments, audio as a voice bubble, anything else as a downloadable document. "
  3966. "Do NOT use markdown image syntax for local files. Local files always go through MEDIA:. "
  3967. "Several images in one response are bundled into a single message. "
  3968. "You can also talk to Chatto unprompted: the plugin tools chatto_list_rooms, "
  3969. "chatto_send_room and chatto_send_dm post to a channel or a person's DM on your "
  3970. "behalf. Only send into a channel that the bot answers in, and reach a person by DM "
  3971. "only once they have written to the bot themselves. "
  3972. ),
  3973. )