adapter.py 179 KB

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