adapter.py 176 KB

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