adapter.py 192 KB

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