adapter.py 152 KB

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