adapter.py 224 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536
  1. # health: allow FILE_LINES -- platform-tables refactor: core's PLATFORM_HINTS/_PLATFORM_DEFAULTS rows for this platform moved onto its register() call (hint text lives in adapter_hint.py); the growth is only those kwargs
  2. """
  3. Feishu/Lark platform adapter.
  4. Supports WebSocket + Webhook transports, DM/@mention-gated group text, inbound
  5. media caching, FEISHU_ALLOWED_USERS allowlisting, persistent dedup, per-chat
  6. serial processing, processing-status reactions (Typing while working, CrossMark
  7. on failure), reaction/card-button events as synthetic events, webhook anomaly
  8. tracking and verification-token validation (all mirroring openclaw).
  9. Feishu identity model (https://open.feishu.cn/document/home/user-identity-introduction/introduction):
  10. open_id (ou_xxx) — app-scoped; differs per Feishu app; always in event payloads.
  11. user_id (u_xxx) — tenant-scoped; needs ``contact:user.employee_id:readonly``; may be absent.
  12. union_id (on_xxx) — developer-scoped; stable across one developer's apps.
  13. Bot: ``app_id`` is the credential; the bot's own open_id (from ``/bot/v3/info``) is
  14. what Feishu puts in ``mentions[].id.open_id`` — used for mention gating only.
  15. Session keys prefer union_id (user_id_alt) over open_id (user_id) for stability.
  16. """
  17. from __future__ import annotations
  18. from pm import install_hint
  19. import asyncio
  20. import collections
  21. import concurrent.futures
  22. import contextvars
  23. import hashlib
  24. import hmac
  25. import itertools
  26. import json
  27. import logging
  28. import mimetypes
  29. import os
  30. import re
  31. import threading
  32. import time
  33. import uuid
  34. from collections import OrderedDict
  35. from dataclasses import dataclass, field
  36. from datetime import datetime
  37. from pathlib import Path
  38. from types import SimpleNamespace
  39. from typing import Any, Dict, List, Literal, Optional, Sequence
  40. from urllib.error import HTTPError, URLError
  41. from urllib.parse import urlencode
  42. from urllib.request import Request, urlopen
  43. # aiohttp/websockets are independent optional deps — import outside lark_oapi
  44. # so they remain available for tests and webhook mode even if lark_oapi is missing.
  45. try:
  46. import aiohttp
  47. from aiohttp import web
  48. except ImportError:
  49. aiohttp = None # type: ignore[assignment]
  50. web = None # type: ignore[assignment]
  51. try:
  52. import websockets
  53. except ImportError:
  54. websockets = None # type: ignore[assignment]
  55. # lark_oapi is slow to import; the SDK names below stay None until Feishu actually connects
  56. # (_load_lark_oapi binds every name in _LARK_SDK_IMPORTS plus ``lark`` and ``FeishuWSClient``).
  57. _LARK_SDK_IMPORTS = (
  58. ("lark_oapi.api.application.v6", ("GetApplicationRequest",)),
  59. ("lark_oapi.api.im.v1", (
  60. "CreateFileRequest", "CreateFileRequestBody", "CreateImageRequest", "CreateImageRequestBody",
  61. "CreateMessageRequest", "CreateMessageRequestBody", "GetChatRequest", "GetMessageRequest",
  62. "DeleteMessageRequest", "GetMessageResourceRequest", "P2ImMessageMessageReadV1",
  63. "ReplyMessageRequest", "ReplyMessageRequestBody",
  64. "UpdateMessageRequest", "UpdateMessageRequestBody", "PatchMessageRequest", "PatchMessageRequestBody",
  65. )),
  66. ("lark_oapi.core", ("AccessTokenType", "HttpMethod")),
  67. ("lark_oapi.core.const", ("FEISHU_DOMAIN", "LARK_DOMAIN")),
  68. ("lark_oapi.core.model", ("BaseRequest",)),
  69. ("lark_oapi.event.callback.model.p2_card_action_trigger", ("CallBackCard", "P2CardActionTriggerResponse")),
  70. ("lark_oapi.event.dispatcher_handler", ("EventDispatcherHandler",)),
  71. )
  72. lark = FeishuWSClient = None # type: ignore[assignment]
  73. globals().update({name: None for _, names in _LARK_SDK_IMPORTS for name in names})
  74. FEISHU_AVAILABLE = False
  75. _lark_import_lock = threading.Lock()
  76. FEISHU_WEBSOCKET_AVAILABLE = websockets is not None
  77. FEISHU_WEBHOOK_AVAILABLE = aiohttp is not None
  78. from gateway.config import Platform, PlatformConfig
  79. from agent.i18n import t
  80. from gateway.platforms.base import (
  81. BasePlatformAdapter, ExecApprovalPrompt, SendResult,
  82. SUPPORTED_DOCUMENT_TYPES, cache_document_from_bytes_async, cache_image_from_url,
  83. cache_audio_from_bytes_async, cache_image_from_bytes_async,
  84. )
  85. from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
  86. from plugins.platforms.feishu.adapter_choice_cards import FeishuChoiceCardsMixin
  87. from gateway.status import acquire_scoped_lock
  88. from gateway.status_scoped_locks import release_scoped_lock
  89. from hermes_constants import get_hermes_home
  90. from utils import atomic_json_write, env_float, env_int
  91. from gateway.platforms._shared import (
  92. apply_yaml_bridge as _apply_yaml_bridge, extra_or_secret as _shared_extra_or_secret,
  93. get_scoped_secret as _get_scoped_secret, send_error
  94. )
  95. logger = logging.getLogger(__name__)
  96. # --- Regex patterns ---
  97. _MARKDOWN_HINT_RE = re.compile(
  98. # Pipe table: any header line + separator line both starting with '|'.
  99. r"(^\|.*\|\s*\n\|[-:|\s]+\|)"
  100. # Headings, lists, code, bold/italic/strike/underline, links, blockquotes.
  101. r"|(^#{1,6}\s)"
  102. r"|(^\s*[-*]\s)"
  103. r"|(^\s*\d+\.\s)"
  104. r"|(^\s*---+\s*$)"
  105. r"|(```)"
  106. r"|(`[^`\n]+`)"
  107. r"|(\*\*[^*\n].+?\*\*)"
  108. r"|(~~[^~\n].+?~~)"
  109. r"|(<u>.+?</u>)"
  110. r"|(\*[^*\n]+\*)"
  111. r"|(\[[^\]]+\]\([^)]+\))"
  112. r"|(^>\s)",
  113. re.MULTILINE,
  114. )
  115. _MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
  116. _MARKDOWN_FENCE_OPEN_RE = re.compile(r"^```([^\n`]*)\s*$")
  117. _MARKDOWN_FENCE_CLOSE_RE = re.compile(r"^```\s*$")
  118. _MULTISPACE_RE = re.compile(r"[ \t]{2,}")
  119. _POST_CONTENT_INVALID_RE = re.compile(r"content format of the post type is incorrect", re.IGNORECASE)
  120. # --- Media type sets and upload constants ---
  121. _IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
  122. _AUDIO_EXTENSIONS = {".ogg", ".mp3", ".wav", ".m4a", ".aac", ".flac", ".opus", ".webm"}
  123. _VIDEO_EXTENSIONS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".m4v", ".3gp"}
  124. _DOCUMENT_MIME_TO_EXT = {mime: ext for ext, mime in SUPPORTED_DOCUMENT_TYPES.items()}
  125. _FEISHU_IMAGE_UPLOAD_TYPE = "message"
  126. _FEISHU_FILE_UPLOAD_TYPE = "stream"
  127. _FEISHU_OPUS_UPLOAD_EXTENSIONS = {".ogg", ".opus"}
  128. _FEISHU_MEDIA_UPLOAD_EXTENSIONS = {".mp4", ".mov", ".avi", ".m4v"}
  129. _FEISHU_DOC_UPLOAD_TYPES = {
  130. ".pdf": "pdf", ".doc": "doc", ".docx": "doc", ".xls": "xls", ".xlsx": "xls", ".ppt": "ppt", ".pptx": "ppt",
  131. }
  132. # --- Connection, retry and batching tuning ---
  133. _MAX_TEXT_INJECT_BYTES = 100 * 1024
  134. _FEISHU_CONNECT_ATTEMPTS = 3
  135. _FEISHU_SEND_ATTEMPTS = 3
  136. _FEISHU_APP_LOCK_SCOPE = "feishu-app-id"
  137. _DEFAULT_TEXT_BATCH_DELAY_SECONDS = 0.6
  138. _DEFAULT_TEXT_BATCH_MAX_MESSAGES = 8
  139. _DEFAULT_TEXT_BATCH_MAX_CHARS = 4000
  140. _DEFAULT_MEDIA_BATCH_DELAY_SECONDS = 0.8
  141. _DEFAULT_DEDUP_CACHE_SIZE = 2048
  142. _DEFAULT_WEBHOOK_HOST = "127.0.0.1"
  143. _DEFAULT_WEBHOOK_PORT = 8765
  144. _DEFAULT_WEBHOOK_PATH = "/feishu/webhook"
  145. # --- TTL, rate-limit and webhook security constants ---
  146. _FEISHU_DEDUP_TTL_SECONDS = 24 * 60 * 60 # 24 hours — matches openclaw
  147. _FEISHU_SENDER_NAME_TTL_SECONDS = 10 * 60 # 10 minutes sender-name cache
  148. _FEISHU_WEBHOOK_MAX_BODY_BYTES = 1 * 1024 * 1024 # 1 MB body limit
  149. _FEISHU_WEBHOOK_RATE_WINDOW_SECONDS = 60 # sliding window for rate limiter
  150. _FEISHU_WEBHOOK_RATE_LIMIT_MAX = 120 # max requests per window per IP — matches openclaw
  151. _FEISHU_WEBHOOK_RATE_MAX_KEYS = 4096 # max tracked keys (prevents unbounded growth)
  152. _FEISHU_WEBHOOK_BODY_TIMEOUT_SECONDS = 30 # max seconds to read request body
  153. _FEISHU_WEBHOOK_ANOMALY_THRESHOLD = 25 # consecutive error responses before WARNING log
  154. _FEISHU_WEBHOOK_ANOMALY_TTL_SECONDS = 6 * 60 * 60 # anomaly tracker TTL (6 hours) — matches openclaw
  155. _FEISHU_CARD_ACTION_DEDUP_TTL_SECONDS = 15 * 60 # card action token dedup window (15 min)
  156. _APPROVAL_CHOICE_MAP: dict[str, str] = {
  157. "approve_once": "once", "approve_session": "session", "approve_always": "always", "deny": "deny",
  158. }
  159. # choice → catalog key of the resolved-card title; looked up through ``t()`` at resolve time.
  160. _APPROVAL_LABEL_KEYS: dict[str, str] = {
  161. "once": "platform.feishu.approval.resolved_once", "session": "platform.feishu.approval.resolved_session",
  162. "always": "platform.feishu.approval.resolved_always", "deny": "platform.feishu.approval.resolved_deny",
  163. }
  164. async def _read_limited_feishu_webhook_body(request: Any, max_bytes: int) -> bytes:
  165. """Read at most ``max_bytes`` from an aiohttp request body."""
  166. try:
  167. body = await request.content.readexactly(max_bytes + 1)
  168. except asyncio.IncompleteReadError as exc:
  169. body = exc.partial
  170. if len(body) > max_bytes:
  171. raise ValueError("payload too large")
  172. return body
  173. _FEISHU_REPLY_FALLBACK_CODES = frozenset({230011, 231003}) # reply target withdrawn/missing → create fallback
  174. # Feishu reactions render as prominent badges, unlike Discord/Telegram's
  175. # small footer emoji — a success badge on every message would add noise, so
  176. # we only mark start (Typing) and failure (CrossMark); the reply itself is
  177. # the success signal.
  178. _FEISHU_REACTION_IN_PROGRESS = "Typing"
  179. _FEISHU_REACTION_FAILURE = "CrossMark"
  180. # Bound on the (message_id → reaction_id) handle cache. Happy-path entries
  181. # drain on completion; the cap is a safeguard against unbounded growth from
  182. # delete-failures, not a capacity plan.
  183. _FEISHU_PROCESSING_REACTION_CACHE_SIZE = 1024
  184. _FEISHU_MESSAGE_TEXT_CACHE_SIZE = 512 # LRU cap for reply-context message text lookups
  185. # QR onboarding constants
  186. _ONBOARD_ACCOUNTS_URLS = {
  187. "feishu": "https://accounts.feishu.cn",
  188. "lark": "https://accounts.larksuite.com",
  189. }
  190. _ONBOARD_OPEN_URLS = {"feishu": "https://open.feishu.cn", "lark": "https://open.larksuite.com"}
  191. _REGISTRATION_PATH = "/oauth/v1/app/registration"
  192. _ONBOARD_REQUEST_TIMEOUT_S = 10
  193. # --- Fallback display strings ---
  194. FALLBACK_POST_TEXT = "[Rich text message]"
  195. FALLBACK_FORWARD_TEXT = "[Merged forward message]"
  196. FALLBACK_SHARE_CHAT_TEXT = "[Shared chat]"
  197. FALLBACK_INTERACTIVE_TEXT = "[Interactive message]"
  198. FALLBACK_IMAGE_TEXT = "[Image]"
  199. FALLBACK_ATTACHMENT_TEXT = "[Attachment]"
  200. # --- Post/card parsing helpers ---
  201. _PREFERRED_LOCALES = ("zh_cn", "en_us")
  202. _MARKDOWN_SPECIAL_CHARS_RE = re.compile(r"([\\`*_{}\[\]()#+\-!|>~])")
  203. _MENTION_PLACEHOLDER_RE = re.compile(r"@_user_\d+")
  204. _MENTION_BOUNDARY_CHARS = frozenset(" \t\n\r.,;:!?、,。;:!?()[]{}<>\"'`")
  205. _TRAILING_TERMINAL_PUNCT = frozenset(" \t\n\r.!?。!?")
  206. _WHITESPACE_RE = re.compile(r"\s+")
  207. _SUPPORTED_CARD_TEXT_KEYS = (
  208. "title", "text", "content", "label", "value", "name", "summary", "subtitle", "description", "placeholder", "hint",
  209. )
  210. _RICH_BLOCK_TAGS = {
  211. "plain_text", "lark_md", "markdown", "note", "div", "column_set", "column", "action", "button", "select_static",
  212. "date_picker",
  213. }
  214. _SKIP_TEXT_KEYS = {
  215. "tag", "type", "msg_type", "message_type", "chat_id", "open_chat_id", "share_chat_id", "file_key", "image_key",
  216. "user_id", "open_id", "union_id", "url", "href", "link", "token", "template", "locale",
  217. }
  218. @dataclass(frozen=True)
  219. class FeishuPostMediaRef:
  220. file_key: str
  221. file_name: str = ""
  222. resource_type: str = "file"
  223. @dataclass(frozen=True)
  224. class FeishuMentionRef:
  225. name: str = ""
  226. open_id: str = ""
  227. is_all: bool = False
  228. is_self: bool = False
  229. @dataclass(frozen=True)
  230. class _FeishuBotIdentity:
  231. open_id: str = ""
  232. user_id: str = ""
  233. name: str = ""
  234. def matches(self, *, open_id: str, user_id: str, name: str) -> bool:
  235. # Precedence: open_id > user_id > name. IDs are authoritative when both
  236. # sides have them; the next tier is only considered when either side
  237. # lacks the current one.
  238. if open_id and self.open_id:
  239. return open_id == self.open_id
  240. if user_id and self.user_id:
  241. return user_id == self.user_id
  242. return bool(self.name) and name == self.name
  243. @dataclass(frozen=True)
  244. class FeishuPostParseResult:
  245. text_content: str
  246. image_keys: list[str] = field(default_factory=list)
  247. media_refs: list[FeishuPostMediaRef] = field(default_factory=list)
  248. @dataclass(frozen=True)
  249. class FeishuNormalizedMessage:
  250. raw_type: str
  251. text_content: str
  252. preferred_message_type: str = "text"
  253. image_keys: list[str] = field(default_factory=list)
  254. media_refs: list[FeishuPostMediaRef] = field(default_factory=list)
  255. mentions: list[FeishuMentionRef] = field(default_factory=list)
  256. relation_kind: str = "plain"
  257. metadata: dict[str, Any] = field(default_factory=dict)
  258. @dataclass(frozen=True)
  259. class FeishuAdapterSettings:
  260. """Every field is mirrored onto the adapter as ``self._<field>`` by ``_apply_settings``."""
  261. app_id: str # credential identifier, never taken from event payloads
  262. app_secret: str
  263. domain_name: str
  264. connection_mode: str
  265. encrypt_key: str
  266. verification_token: str
  267. group_policy: str
  268. allowed_group_users: frozenset[str]
  269. bot_open_id: str # app-scoped id from /bot/v3/info — what mentions[].id.open_id carries
  270. bot_user_id: str # tenant-scoped fallback for mention matching
  271. bot_name: str
  272. dedup_cache_size: int
  273. text_batch_delay_seconds: float
  274. text_batch_split_delay_seconds: float
  275. text_batch_max_messages: int
  276. text_batch_max_chars: int
  277. media_batch_delay_seconds: float
  278. webhook_host: str
  279. webhook_port: int
  280. webhook_path: str
  281. ws_reconnect_nonce: int = 30
  282. ws_reconnect_interval: int = 120
  283. ws_ping_interval: Optional[int] = None
  284. ws_ping_timeout: Optional[int] = None
  285. admins: frozenset[str] = frozenset()
  286. default_group_policy: str = ""
  287. group_rules: dict[str, FeishuGroupRule] = field(default_factory=dict)
  288. allow_bots: str = "none" # "none" | "mentions" | "all"
  289. require_mention: bool = True
  290. allow_all_dm: bool = False # resolved per-profile so multiplexed adapters honor their own .env
  291. @dataclass
  292. class FeishuGroupRule:
  293. """Per-group policy rule for controlling which users may interact with the bot."""
  294. policy: str # "open" | "allowlist" | "blacklist" | "admin_only" | "disabled"
  295. allowlist: set[str] = field(default_factory=set)
  296. blacklist: set[str] = field(default_factory=set)
  297. require_mention: Optional[bool] = None # None = inherit global
  298. @dataclass
  299. class FeishuBatchState:
  300. events: dict[str, MessageEvent] = field(default_factory=dict)
  301. tasks: dict[str, asyncio.Task] = field(default_factory=dict)
  302. counts: dict[str, int] = field(default_factory=dict)
  303. # --- Admission: policy types ---
  304. RejectReason = Literal["self_echo", "self_ids_unknown", "bots_disabled", "bot_not_mentioned", "group_policy_rejected"]
  305. def _is_bot_sender(sender: Any) -> bool:
  306. # receive_v1 docs say {user, bot}; accept "app" defensively.
  307. return getattr(sender, "sender_type", "") in {"bot", "app"}
  308. def _sender_identity(sender: Any) -> frozenset:
  309. # Take any non-empty id variant — tenant sender_id_type decides which are populated.
  310. sid = getattr(sender, "sender_id", None)
  311. if sid is None:
  312. return frozenset()
  313. return frozenset(v for v in (getattr(sid, k, None) for k in ("open_id", "user_id", "union_id")) if v)
  314. # --- Markdown rendering helpers ---
  315. def _escape_markdown_text(text: str) -> str:
  316. return _MARKDOWN_SPECIAL_CHARS_RE.sub(r"\\\1", text)
  317. def _to_boolean(value: Any) -> bool:
  318. return value is True or value == 1 or value == "true"
  319. def _is_style_enabled(style: dict[str, Any] | None, key: str) -> bool:
  320. if not style:
  321. return False
  322. return _to_boolean(style.get(key))
  323. def _wrap_inline_code(text: str) -> str:
  324. max_run = max([0, *[len(run) for run in re.findall(r"`+", text)]])
  325. fence = "`" * (max_run + 1)
  326. body = f" {text} " if text.startswith("`") or text.endswith("`") else text
  327. return f"{fence}{body}{fence}"
  328. def _sanitize_fence_language(language: str) -> str:
  329. return language.strip().replace("\n", " ").replace("\r", " ")
  330. _TEXT_STYLE_WRAPPERS = (("bold", "**", "**"), ("italic", "*", "*"), ("underline", "<u>", "</u>"), ("strikethrough", "~~", "~~"))
  331. def _render_text_element(element: dict[str, Any]) -> str:
  332. text = str(element.get("text", "") or "")
  333. style = element.get("style")
  334. style_dict = style if isinstance(style, dict) else None
  335. if _is_style_enabled(style_dict, "code"):
  336. return _wrap_inline_code(text)
  337. # Post text elements carry raw text plus separate style flags; the style wrappers below
  338. # re-create the markdown. Escaping the text here put `\*\*bold\*\*` / `\`code\`` into the
  339. # model's context and those backslashes came straight back out in replies (#9816).
  340. rendered = text
  341. if not rendered:
  342. return ""
  343. for key, prefix, suffix in _TEXT_STYLE_WRAPPERS: # order matters for nesting
  344. if _is_style_enabled(style_dict, key):
  345. rendered = f"{prefix}{rendered}{suffix}"
  346. return rendered
  347. def _render_code_block_element(element: dict[str, Any]) -> str:
  348. language = _sanitize_fence_language(str(element.get("language", "") or "") or str(element.get("lang", "") or ""))
  349. code = (str(element.get("text", "") or "") or str(element.get("content", "") or "")).replace("\r\n", "\n")
  350. trailing_newline = "" if code.endswith("\n") else "\n"
  351. return f"```{language}\n{code}{trailing_newline}```"
  352. def _strip_markdown_to_plain_text(text: str) -> str:
  353. """Plain-text fallback: shared strip_markdown plus Feishu extras (blockquote, ~~, <u>, hr, CRLF)."""
  354. from gateway.platforms.helpers import strip_markdown
  355. plain = text.replace("\r\n", "\n")
  356. plain = _MARKDOWN_LINK_RE.sub(lambda m: f"{m.group(1)} ({m.group(2).strip()})", plain)
  357. plain = re.sub(r"^>\s?", "", plain, flags=re.MULTILINE)
  358. plain = re.sub(r"^\s*---+\s*$", "---", plain, flags=re.MULTILINE)
  359. plain = re.sub(r"~~([^~\n]+)~~", r"\1", plain)
  360. plain = re.sub(r"<u>([\s\S]*?)</u>", r"\1", plain)
  361. return strip_markdown(plain)
  362. def _coerce_int(value: Any, default: Optional[int] = None, min_value: int = 0) -> Optional[int]:
  363. """Coerce value to int with optional default and minimum constraint."""
  364. try:
  365. parsed = int(value)
  366. except (TypeError, ValueError):
  367. return default
  368. return parsed if parsed >= min_value else default
  369. def _coerce_required_int(value: Any, default: int, min_value: int = 0) -> int:
  370. parsed = _coerce_int(value, default=default, min_value=min_value)
  371. return default if parsed is None else parsed
  372. # --- Post payload builders and parsers ---
  373. def _build_markdown_post_payload(content: str) -> str:
  374. rows = _build_markdown_post_rows(content)
  375. return json.dumps({"zh_cn": {"content": rows}}, ensure_ascii=False)
  376. def _build_markdown_post_rows(content: str) -> list[list[dict[str, str]]]:
  377. """Build Feishu post rows, giving each fenced code block its own row.
  378. Feishu's `md` renderer can swallow trailing content when a fence sits inside one
  379. large element; splitting at real fence lines keeps surrounding prose visible.
  380. """
  381. if not content:
  382. return [[{"tag": "md", "text": ""}]]
  383. if "```" not in content:
  384. return [[{"tag": "md", "text": content}]]
  385. rows: list[list[dict[str, str]]] = []
  386. current: list[str] = []
  387. in_code_block = False
  388. def _flush_current() -> None:
  389. nonlocal current
  390. segment = "\n".join(current)
  391. if segment.strip():
  392. rows.append([{"tag": "md", "text": segment}])
  393. current = []
  394. for raw_line in content.splitlines():
  395. fence_re = _MARKDOWN_FENCE_CLOSE_RE if in_code_block else _MARKDOWN_FENCE_OPEN_RE
  396. is_fence = bool(fence_re.match(raw_line.strip()))
  397. if is_fence and not in_code_block: # opening fence: prose before it becomes its own row
  398. _flush_current()
  399. current.append(raw_line)
  400. if is_fence:
  401. in_code_block = not in_code_block
  402. if not in_code_block: # closing fence: the code block becomes its own row
  403. _flush_current()
  404. _flush_current()
  405. return rows or [[{"tag": "md", "text": content}]]
  406. def parse_feishu_post_payload(
  407. payload: Any, *, mentions_map: Optional[dict[str, FeishuMentionRef]] = None,
  408. ) -> FeishuPostParseResult:
  409. resolved = _resolve_post_payload(payload)
  410. if not resolved:
  411. return FeishuPostParseResult(text_content=FALLBACK_POST_TEXT)
  412. image_keys: list[str] = []
  413. media_refs: list[FeishuPostMediaRef] = []
  414. parts: list[str] = []
  415. title = _normalize_feishu_text(str(resolved.get("title", "")).strip())
  416. if title:
  417. parts.append(title)
  418. for row in resolved.get("content", []) or []:
  419. if not isinstance(row, list):
  420. continue
  421. row_text = _normalize_feishu_text(
  422. "".join(_render_post_element(item, image_keys, media_refs, mentions_map) for item in row)
  423. )
  424. if row_text:
  425. parts.append(row_text)
  426. for entry in resolved.get("files", []) or []:
  427. if (
  428. not isinstance(entry, dict)
  429. or _to_boolean(entry.get("is_folder"))
  430. or not str(entry.get("file_key", "")).strip()
  431. ):
  432. continue
  433. placeholder = _render_post_element(
  434. {**entry, "tag": "file"}, image_keys, media_refs, mentions_map,
  435. )
  436. if placeholder:
  437. parts.append(placeholder)
  438. return FeishuPostParseResult(
  439. text_content="\n".join(parts).strip() or FALLBACK_POST_TEXT, image_keys=image_keys, media_refs=media_refs,
  440. )
  441. def _resolve_post_payload(payload: Any) -> dict[str, Any]:
  442. direct = _to_post_payload(payload)
  443. if direct:
  444. return direct
  445. if not isinstance(payload, dict):
  446. return {}
  447. return _resolve_locale_payload(payload.get("post")) or _resolve_locale_payload(payload)
  448. def _resolve_locale_payload(payload: Any) -> dict[str, Any]:
  449. direct = _to_post_payload(payload)
  450. if direct:
  451. return direct
  452. if not isinstance(payload, dict):
  453. return {}
  454. # Preferred locales first, then any locale that carries a content list.
  455. preferred = (payload.get(key) for key in _PREFERRED_LOCALES)
  456. for candidate in map(_to_post_payload, itertools.chain(preferred, payload.values())):
  457. if candidate:
  458. return candidate
  459. return {}
  460. def _to_post_payload(candidate: Any) -> dict[str, Any]:
  461. if not isinstance(candidate, dict):
  462. return {}
  463. content = candidate.get("content")
  464. if not isinstance(content, list):
  465. return {}
  466. files = candidate.get("files")
  467. return {
  468. "title": str(candidate.get("title", "") or ""),
  469. "content": content,
  470. "files": files if isinstance(files, list) else [],
  471. }
  472. _STATIC_POST_TAGS = {"br": "\n", "hr": "\n\n---\n\n", "divider": "\n\n---\n\n"}
  473. def _render_post_element(
  474. element: Any, image_keys: list[str], media_refs: list[FeishuPostMediaRef],
  475. mentions_map: Optional[dict[str, FeishuMentionRef]] = None,
  476. ) -> str:
  477. if isinstance(element, str):
  478. return element
  479. if not isinstance(element, dict):
  480. return ""
  481. tag = str(element.get("tag", "")).strip().lower()
  482. if tag in _STATIC_POST_TAGS:
  483. return _STATIC_POST_TAGS[tag]
  484. if tag == "text":
  485. return _render_text_element(element)
  486. if tag in {"code_block", "pre"}:
  487. return _render_code_block_element(element)
  488. if tag == "a":
  489. href = str(element.get("href", "")).strip()
  490. label = str(element.get("text", href) or "").strip()
  491. if not label:
  492. return ""
  493. escaped_label = _escape_markdown_text(label)
  494. return f"[{escaped_label}]({href})" if href else escaped_label
  495. if tag == "at":
  496. # <at>.user_id is a placeholder ("@_user_N" / "@_all"); mentions_map has the real ref.
  497. placeholder = str(element.get("user_id", "")).strip()
  498. if placeholder == "@_all":
  499. # The SDK sometimes omits @_all from top-level mentions; record it so callers see it.
  500. if mentions_map is not None and "@_all" not in mentions_map:
  501. mentions_map["@_all"] = FeishuMentionRef(is_all=True)
  502. return "@all"
  503. ref = (mentions_map or {}).get(placeholder)
  504. display_name = (ref.name or ref.open_id or "user") if ref is not None else (
  505. str(element.get("user_name", "")).strip() or "user"
  506. )
  507. return f"@{_escape_markdown_text(display_name)}"
  508. if tag in {"img", "image"}:
  509. image_key = str(element.get("image_key", "")).strip()
  510. if image_key and image_key not in image_keys:
  511. image_keys.append(image_key)
  512. alt = str(element.get("text", "")).strip() or str(element.get("alt", "")).strip()
  513. return f"[Image: {alt}]" if alt else "[Image]"
  514. if tag in {"media", "file", "audio", "video"}:
  515. file_key = str(element.get("file_key", "")).strip()
  516. names = (str(element.get(k, "")).strip() for k in ("file_name", "title", "text"))
  517. file_name = next((n for n in names if n), "")
  518. placeholder = f"[Attachment: {file_name}]" if file_name else "[Attachment]"
  519. if not file_key:
  520. return placeholder
  521. if not any(ref.file_key == file_key for ref in media_refs):
  522. media_refs.append(FeishuPostMediaRef(
  523. file_key=file_key, file_name=file_name, resource_type=tag if tag in {"audio", "video"} else "file",
  524. ))
  525. return placeholder
  526. return ""
  527. if tag in {"emotion", "emoji"}:
  528. label = str(element.get("text", "")).strip() or str(element.get("emoji_type", "")).strip()
  529. return f":{_escape_markdown_text(label)}:" if label else "[Emoji]"
  530. if tag == "code":
  531. code = str(element.get("text", "") or "") or str(element.get("content", "") or "")
  532. return _wrap_inline_code(code) if code else ""
  533. nested = (element.get(key) for key in ("text", "title", "content", "children", "elements"))
  534. return _join_nested_posts(nested, image_keys, media_refs, mentions_map)
  535. def _join_nested_posts(values: Any, image_keys: Any, media_refs: Any, mentions_map: Any) -> str:
  536. parts = (_render_nested_post(item, image_keys, media_refs, mentions_map) for item in values)
  537. return " ".join(part for part in parts if part)
  538. def _render_nested_post(
  539. value: Any, image_keys: list[str], media_refs: list[FeishuPostMediaRef],
  540. mentions_map: Optional[dict[str, FeishuMentionRef]] = None,
  541. ) -> str:
  542. if isinstance(value, str):
  543. return _escape_markdown_text(value)
  544. if isinstance(value, list):
  545. return _join_nested_posts(value, image_keys, media_refs, mentions_map)
  546. if isinstance(value, dict):
  547. direct = _render_post_element(value, image_keys, media_refs, mentions_map)
  548. return direct or _join_nested_posts(value.values(), image_keys, media_refs, mentions_map)
  549. return ""
  550. # --- Message normalization ---
  551. def normalize_feishu_message(
  552. *, message_type: str, raw_content: str, mentions: Optional[Sequence[Any]] = None,
  553. bot: _FeishuBotIdentity = _FeishuBotIdentity(),
  554. ) -> FeishuNormalizedMessage:
  555. normalized_type = str(message_type or "").strip().lower()
  556. payload = _load_feishu_payload(raw_content)
  557. mentions_map = _build_mentions_map(mentions, bot)
  558. if normalized_type == "text":
  559. text = str(payload.get("text", "") or "")
  560. # Feishu SDK sometimes omits @_all from the mentions payload even when
  561. # the text literal contains it (confirmed via im.v1.message.get).
  562. if "@_all" in text and "@_all" not in mentions_map:
  563. mentions_map["@_all"] = FeishuMentionRef(is_all=True)
  564. return FeishuNormalizedMessage(
  565. raw_type=normalized_type, text_content=_normalize_feishu_text(text, mentions_map),
  566. mentions=list(mentions_map.values()),
  567. )
  568. if normalized_type == "post":
  569. # The walker writes back to mentions_map if it encounters
  570. # <at user_id="@_all">, so reading .values() after parsing is enough.
  571. parsed_post = parse_feishu_post_payload(payload, mentions_map=mentions_map)
  572. return FeishuNormalizedMessage(
  573. raw_type=normalized_type, text_content=parsed_post.text_content,
  574. image_keys=list(parsed_post.image_keys), media_refs=list(parsed_post.media_refs),
  575. mentions=list(mentions_map.values()), relation_kind="post",
  576. )
  577. mention_refs = list(mentions_map.values())
  578. if normalized_type == "image":
  579. image_key = str(payload.get("image_key", "") or "").strip()
  580. alt_text = _normalize_feishu_text(
  581. str(payload.get("text", "") or "")
  582. or str(payload.get("alt", "") or "")
  583. or FALLBACK_IMAGE_TEXT,
  584. mentions_map,
  585. )
  586. return FeishuNormalizedMessage(
  587. raw_type=normalized_type,
  588. text_content=alt_text if alt_text != FALLBACK_IMAGE_TEXT else "",
  589. preferred_message_type="photo", image_keys=[image_key] if image_key else [],
  590. relation_kind="image", mentions=mention_refs,
  591. )
  592. if normalized_type in {"file", "audio", "media"}:
  593. media_ref = _build_media_ref_from_payload(payload, resource_type=normalized_type)
  594. return FeishuNormalizedMessage(
  595. raw_type=normalized_type, text_content="",
  596. preferred_message_type="audio" if normalized_type == "audio" else "document",
  597. media_refs=[media_ref] if media_ref.file_key else [], relation_kind=normalized_type,
  598. metadata={"placeholder_text": _attachment_placeholder(media_ref.file_name)},
  599. mentions=mention_refs,
  600. )
  601. if normalized_type == "merge_forward":
  602. return _normalize_merge_forward_message(payload)
  603. if normalized_type == "share_chat":
  604. return _normalize_share_chat_message(payload)
  605. if normalized_type in {"interactive", "card"}:
  606. return _normalize_interactive_message(normalized_type, payload)
  607. return FeishuNormalizedMessage(raw_type=normalized_type, text_content="")
  608. def _load_feishu_payload(raw_content: str) -> dict[str, Any]:
  609. try:
  610. parsed = json.loads(raw_content) if raw_content else {}
  611. except json.JSONDecodeError:
  612. return {"text": raw_content}
  613. return parsed if isinstance(parsed, dict) else {"content": parsed}
  614. def _normalize_merge_forward_message(payload: dict[str, Any]) -> FeishuNormalizedMessage:
  615. title = _first_text_field(payload, "title", "summary", "preview", deep=("title", "summary", "preview", "description"))
  616. entries = _collect_forward_entries(payload)
  617. lines = ([title] if title else []) + entries[:8]
  618. return FeishuNormalizedMessage(
  619. raw_type="merge_forward", text_content="\n".join(lines).strip() or FALLBACK_FORWARD_TEXT,
  620. relation_kind="merge_forward", metadata={"entry_count": len(entries), "title": title},
  621. )
  622. def _normalize_share_chat_message(payload: dict[str, Any]) -> FeishuNormalizedMessage:
  623. chat_name = _first_text_field(payload, "chat_name", "name", "title", deep=("chat_name", "name", "title"))
  624. share_id = _first_text_field(payload, "chat_id", "open_chat_id", "share_chat_id")
  625. lines = [f"Shared chat: {chat_name}" if chat_name else FALLBACK_SHARE_CHAT_TEXT]
  626. if share_id:
  627. lines.append(f"Chat ID: {share_id}")
  628. return FeishuNormalizedMessage(
  629. raw_type="share_chat", text_content="\n".join(lines), relation_kind="share_chat",
  630. metadata={"chat_id": share_id, "chat_name": chat_name},
  631. )
  632. def _normalize_interactive_message(message_type: str, payload: dict[str, Any]) -> FeishuNormalizedMessage:
  633. card_payload = payload.get("card") if isinstance(payload.get("card"), dict) else payload
  634. title = _first_non_empty_text(
  635. _find_header_title(card_payload), payload.get("title"),
  636. _find_first_text(card_payload, keys=("title", "summary", "subtitle")),
  637. )
  638. actions = _collect_action_labels(card_payload)
  639. lines = ([title] if title else []) + [line for line in _collect_card_lines(card_payload) if line != title]
  640. if actions:
  641. lines.append(f"Actions: {', '.join(actions)}")
  642. return FeishuNormalizedMessage(
  643. raw_type=message_type,
  644. text_content="\n".join(lines[:12]).strip() or FALLBACK_INTERACTIVE_TEXT,
  645. relation_kind="interactive", metadata={"title": title, "actions": actions},
  646. )
  647. # --- Content extraction utilities (card / forward / text walking) ---
  648. def _collect_forward_entries(payload: dict[str, Any]) -> list[str]:
  649. candidates: list[Any] = []
  650. for key in ("messages", "items", "message_list", "records", "content"):
  651. value = payload.get(key)
  652. if isinstance(value, list):
  653. candidates.extend(value)
  654. entries: list[str] = []
  655. for item in candidates:
  656. if not isinstance(item, dict):
  657. text = _normalize_feishu_text(str(item or ""))
  658. if text:
  659. entries.append(f"- {text}")
  660. continue
  661. sender = _first_text_field(item, "sender_name", "user_name", "sender", "name")
  662. nested_type = str(item.get("message_type", "") or item.get("msg_type", "")).strip().lower()
  663. if nested_type == "post":
  664. body = parse_feishu_post_payload(item.get("content") or item).text_content
  665. else:
  666. body = _first_text_field(
  667. item, "text", "summary", "preview", "content", deep=("text", "content", "summary", "preview", "title"),
  668. )
  669. body = _normalize_feishu_text(body)
  670. if sender and body:
  671. entries.append(f"- {sender}: {body}")
  672. elif body:
  673. entries.append(f"- {body}")
  674. return _unique_lines(entries)
  675. def _collect_card_lines(payload: Any) -> list[str]:
  676. lines = _collect_text_segments(payload, in_rich_block=False)
  677. normalized = [_normalize_feishu_text(line) for line in lines]
  678. return _unique_lines([line for line in normalized if line])
  679. def _collect_action_labels(payload: Any) -> list[str]:
  680. labels: list[str] = []
  681. for item in _walk_nodes(payload):
  682. if not isinstance(item, dict):
  683. continue
  684. tag = str(item.get("tag", "") or item.get("type", "")).strip().lower()
  685. if tag not in {"button", "select_static", "overflow", "date_picker", "picker"}:
  686. continue
  687. label = _first_text_field(item, "text", "name", "value", deep=("text", "content", "name", "value"))
  688. if label:
  689. labels.append(label)
  690. return _unique_lines(labels)
  691. def _collect_text_segments(value: Any, *, in_rich_block: bool) -> list[str]:
  692. if isinstance(value, str):
  693. return [_normalize_feishu_text(value)] if in_rich_block else []
  694. if isinstance(value, list):
  695. return [seg for item in value for seg in _collect_text_segments(item, in_rich_block=in_rich_block)]
  696. if not isinstance(value, dict):
  697. return []
  698. tag = str(value.get("tag", "") or value.get("type", "")).strip().lower()
  699. next_in_rich_block = in_rich_block or tag in _RICH_BLOCK_TAGS
  700. segments: list[str] = []
  701. if next_in_rich_block:
  702. for key in _SUPPORTED_CARD_TEXT_KEYS:
  703. item = value.get(key)
  704. if isinstance(item, str) and _normalize_feishu_text(item):
  705. segments.append(_normalize_feishu_text(item))
  706. for key, item in value.items():
  707. if key not in _SKIP_TEXT_KEYS:
  708. segments.extend(_collect_text_segments(item, in_rich_block=next_in_rich_block))
  709. return segments
  710. def _build_media_ref_from_payload(payload: dict[str, Any], *, resource_type: str) -> FeishuPostMediaRef:
  711. file_key = str(payload.get("file_key", "") or "").strip()
  712. file_name = _first_text_field(payload, "file_name", "title", "text")
  713. effective_type = resource_type if resource_type in {"audio", "video"} else "file"
  714. return FeishuPostMediaRef(file_key=file_key, file_name=file_name, resource_type=effective_type)
  715. def _attachment_placeholder(file_name: str) -> str:
  716. normalized_name = _normalize_feishu_text(file_name)
  717. return f"[Attachment: {normalized_name}]" if normalized_name else FALLBACK_ATTACHMENT_TEXT
  718. def _find_header_title(payload: Any) -> str:
  719. if not isinstance(payload, dict):
  720. return ""
  721. header = payload.get("header")
  722. if not isinstance(header, dict):
  723. return ""
  724. title = header.get("title")
  725. if isinstance(title, dict):
  726. return _first_non_empty_text(title.get("content"), title.get("text"), title.get("name"))
  727. return _normalize_feishu_text(str(title or ""))
  728. def _find_first_text(payload: Any, *, keys: tuple[str, ...]) -> str:
  729. for node in _walk_nodes(payload):
  730. if not isinstance(node, dict):
  731. continue
  732. for key in keys:
  733. value = node.get(key)
  734. if isinstance(value, str):
  735. normalized = _normalize_feishu_text(value)
  736. if normalized:
  737. return normalized
  738. return ""
  739. def _walk_nodes(value: Any):
  740. if isinstance(value, dict):
  741. yield value
  742. for item in value.values():
  743. yield from _walk_nodes(item)
  744. elif isinstance(value, list):
  745. for item in value:
  746. yield from _walk_nodes(item)
  747. def _first_non_empty_text(*values: Any) -> str:
  748. """First scalar (non-dict/list, non-None) value that normalizes to non-empty text."""
  749. for value in values:
  750. if value is None or isinstance(value, (dict, list)):
  751. continue
  752. normalized = _normalize_feishu_text(value if isinstance(value, str) else str(value))
  753. if normalized:
  754. return normalized
  755. return ""
  756. def _first_text_field(payload: dict[str, Any], *keys: str, deep: tuple[str, ...] = ()) -> str:
  757. """``_first_non_empty_text`` over ``payload[key]`` for each key, then a deep ``_find_first_text``."""
  758. values = [payload.get(key) for key in keys]
  759. if deep:
  760. values.append(_find_first_text(payload, keys=deep))
  761. return _first_non_empty_text(*values)
  762. # --- General text utilities ---
  763. def _normalize_feishu_text(text: str, mentions_map: Optional[dict[str, FeishuMentionRef]] = None) -> str:
  764. def _sub(match: re.Match[str]) -> str:
  765. ref = (mentions_map or {}).get(match.group(0))
  766. return " " if ref is None else f"@{ref.name or ref.open_id or 'user'}"
  767. cleaned = _MENTION_PLACEHOLDER_RE.sub(_sub, text or "")
  768. cleaned = cleaned.replace("@_all", "@all")
  769. cleaned = cleaned.replace("\r\n", "\n").replace("\r", "\n")
  770. cleaned = "\n".join(_WHITESPACE_RE.sub(" ", line).strip() for line in cleaned.split("\n"))
  771. cleaned = "\n".join(line for line in cleaned.split("\n") if line)
  772. cleaned = _MULTISPACE_RE.sub(" ", cleaned)
  773. return cleaned.strip()
  774. def _unique_lines(lines: list[str]) -> list[str]:
  775. seen: set[str] = set()
  776. unique: list[str] = []
  777. for line in lines:
  778. if not line or line in seen:
  779. continue
  780. seen.add(line)
  781. unique.append(line)
  782. return unique
  783. # --- Mention helpers ---
  784. def _extract_mention_ids(mention: Any) -> tuple[str, str]:
  785. """(open_id, user_id): message.get gives a string id + id_type; events give a nested UserId object."""
  786. mention_id = getattr(mention, "id", None)
  787. if isinstance(mention_id, str):
  788. id_type = str(getattr(mention, "id_type", "") or "").lower()
  789. return (mention_id, "") if id_type == "open_id" else ("", mention_id) if id_type == "user_id" else ("", "")
  790. if mention_id is None:
  791. return "", ""
  792. return str(getattr(mention_id, "open_id", "") or ""), str(getattr(mention_id, "user_id", "") or "")
  793. def _build_mentions_map(mentions: Optional[Sequence[Any]], bot: _FeishuBotIdentity) -> dict[str, FeishuMentionRef]:
  794. result: dict[str, FeishuMentionRef] = {}
  795. for mention in mentions or []:
  796. key = str(getattr(mention, "key", "") or "")
  797. if not key:
  798. continue
  799. if key == "@_all":
  800. result[key] = FeishuMentionRef(is_all=True)
  801. continue
  802. open_id, user_id = _extract_mention_ids(mention)
  803. name = str(getattr(mention, "name", "") or "").strip()
  804. is_self = bot.matches(open_id=open_id, user_id=user_id, name=name)
  805. result[key] = FeishuMentionRef(name=name, open_id=open_id, is_self=is_self)
  806. return result
  807. def _build_mention_hint(mentions: Sequence[FeishuMentionRef]) -> str:
  808. parts: list[str] = []
  809. seen: set = set()
  810. for ref in mentions:
  811. if ref.is_self:
  812. continue
  813. signature = (ref.is_all, ref.open_id, ref.name)
  814. if signature in seen:
  815. continue
  816. seen.add(signature)
  817. if ref.is_all:
  818. parts.append("@all")
  819. elif ref.open_id:
  820. parts.append(f"{ref.name or 'unknown'} (open_id={ref.open_id})")
  821. else:
  822. parts.append(ref.name or "unknown")
  823. return f"[Mentioned: {', '.join(parts)}]" if parts else ""
  824. def _strip_edge_self_mentions(text: str, mentions: Sequence[FeishuMentionRef]) -> str:
  825. # Leading self-mentions are stripped unconditionally (word-boundary so @Al can't eat @Alice);
  826. # trailing ones only when followed by whitespace/terminal punct so "don't @Bot again" survives.
  827. if not text:
  828. return text
  829. self_names = [f"@{ref.name or ref.open_id or 'user'}" for ref in mentions if ref.is_self]
  830. if not self_names:
  831. return text
  832. remaining = text.lstrip()
  833. while True:
  834. for nm in self_names:
  835. if not remaining.startswith(nm):
  836. continue
  837. after = remaining[len(nm):]
  838. if after and after[0] not in _MENTION_BOUNDARY_CHARS:
  839. continue
  840. remaining = after.lstrip()
  841. break
  842. else:
  843. break
  844. while True:
  845. i = len(remaining)
  846. while i > 0 and remaining[i - 1] in _TRAILING_TERMINAL_PUNCT:
  847. i -= 1
  848. body = remaining[:i]
  849. tail = remaining[i:]
  850. for nm in self_names:
  851. if body.endswith(nm):
  852. remaining = body[: -len(nm)].rstrip() + tail
  853. break
  854. else:
  855. return remaining
  856. # --- Multiplex isolation for the lark_oapi WebSocket client ---
  857. #
  858. # ``lark_oapi.ws.client`` keeps the asyncio loop in a *module-level global* (``loop``), and
  859. # Hermes monkey-patches ``websockets.connect`` on the shared module to inject ping settings.
  860. # In multiplex mode N profiles each run a WS client on their own thread, so they overwrite
  861. # each other's globals (last-write-wins): tasks land on a sibling's loop ("Future attached
  862. # to a different loop") or a client binds the wrong loop and goes deaf. Fix: install
  863. # process-wide, thread-dispatching shims exactly once —
  864. # * ``ws_client_module.loop`` becomes a proxy forwarding to the loop registered by the
  865. # *current thread* (all SDK reads happen on the loop-owning thread); unregistered
  866. # threads fall back to the SDK's original loop.
  867. # * ``websockets.connect`` becomes one dispatcher that merges the calling thread's
  868. # registered ping overrides, so profiles stop racing over the global patch.
  869. # --------------------------------------------------------------------------- Multiplex isolation for the
  870. # lark_oapi WebSocket client (#73779)
  871. # --------------------------------------------------------------------------- ``lark_oapi.ws.client`` keeps
  872. # the asyncio loop used by ``Client.start()`` and every coroutine it spawns in a *module-level global*
  873. # (``loop``), and Hermes also monkey-patches ``websockets.connect`` on the shared ``websockets`` module to
  874. # inject per-adapter ping settings. In multiplex mode every profile runs its own WS client on a dedicated
  875. # thread, so the N threads overwrite each other's module globals (last-write-wins): a client ends up
  876. # scheduling tasks on a sibling profile's loop ("Future attached to a different loop" crashes) or binds to
  877. # the wrong loop at construction time and goes deaf from the start. The fix installs process-wide,
  878. # thread-dispatching shims exactly once: * ``ws_client_module.loop`` becomes a proxy that forwards every
  879. # attribute access to the loop registered by the *current thread*. All SDK reads of the global happen on the
  880. # thread that owns the loop (``start()`` blocks in ``run_until_complete`` and every ``create_task`` callback
  881. # runs on the loop's own thread), so each profile transparently sees its own loop. Threads that never
  882. # registered one (single-profile installs, CLI) fall back to the SDK's original module loop. *
  883. # ``websockets.connect`` becomes a single dispatcher that merges the per-thread ping overrides registered by
  884. # the calling profile, so profiles no longer race over the global patch or restore each other's hooks while
  885. # a sibling is still connected.
  886. _WS_ISOLATION_LOCK = threading.Lock()
  887. _WS_ISOLATION_INSTALLED = False
  888. _ws_isolation_state = threading.local() # per WS thread: .loop and .connect_kwargs
  889. class _ThreadLocalLoopProxy:
  890. """Forwards attribute access to the current thread's registered loop."""
  891. def __init__(self, fallback: Any) -> None:
  892. self._fallback = fallback
  893. def _target(self) -> Any:
  894. return getattr(_ws_isolation_state, "loop", None) or self._fallback
  895. def __getattr__(self, name: str) -> Any:
  896. return getattr(self._target(), name)
  897. def __repr__(self) -> str: # pragma: no cover - debugging aid
  898. return f"<ThreadLocalLoopProxy target={self._target()!r}>"
  899. def _install_lark_ws_isolation(ws_client_module: Any) -> None:
  900. """Install the thread-dispatching shims once per process (idempotent)."""
  901. global _WS_ISOLATION_INSTALLED
  902. with _WS_ISOLATION_LOCK:
  903. if _WS_ISOLATION_INSTALLED:
  904. return
  905. ws_client_module.loop = _ThreadLocalLoopProxy(ws_client_module.loop)
  906. real_connect = ws_client_module.websockets.connect
  907. def _dispatch_connect(*args: Any, **kwargs: Any) -> Any:
  908. overrides = getattr(_ws_isolation_state, "connect_kwargs", None) or {}
  909. for key, value in overrides.items():
  910. kwargs.setdefault(key, value)
  911. return real_connect(*args, **kwargs)
  912. # Keep inspect.signature(websockets.connect) honest — the SDK probes it for ``proxy`` support.
  913. _dispatch_connect.__wrapped__ = real_connect
  914. _dispatch_connect.__name__ = getattr(real_connect, "__name__", "connect")
  915. ws_client_module.websockets.connect = _dispatch_connect
  916. original_receive_loop = ws_client_module.Client._receive_message_loop
  917. async def _receive_message_loop_exit_notify(self: Any) -> None:
  918. # The SDK schedules this coroutine right after the websocket handshake succeeded, so its
  919. # entry is the only in-thread proof that a (re)built link is actually up.
  920. on_link_up = getattr(_ws_isolation_state, "on_link_up", None)
  921. if on_link_up is not None:
  922. on_link_up()
  923. try:
  924. await original_receive_loop(self)
  925. except Exception:
  926. # ``Client.start()`` parks in ``run_until_complete(_select())``, which only returns
  927. # when this worker loop stops, and the receive loop runs as a bare ``create_task``
  928. # whose exception nobody retrieves — so every unrecoverable exit (reconnect ladder
  929. # disabled, or its ``ClientException``/``ServerUnreachableException`` re-raise)
  930. # left a deaf-but-ESTABLISHED socket whose executor future never completed and the
  931. # supervisor never rebuilt (#113662). Log the root cause here and stop the loop so
  932. # ``start()`` raises, the future completes and ``_supervise_websocket_thread`` fires.
  933. # A *normal* return means the SDK's own ladder already reconnected (it scheduled a
  934. # fresh receive loop) and must NOT stop the loop. Deliberate disconnects nil
  935. # ``_ws_client`` first, so the supervisor exits without restarting.
  936. adapter = getattr(_ws_isolation_state, "adapter", None)
  937. if adapter is None or getattr(adapter, "_running", True):
  938. logger.exception(
  939. "[Feishu] lark WS receive loop died; stopping the worker "
  940. "loop so the supervisor can rebuild"
  941. )
  942. else:
  943. # ``disconnect()`` sent the CLOSE frame itself: the loop ending here is expected.
  944. logger.debug("[Feishu] lark WS receive loop ended during disconnect", exc_info=True)
  945. asyncio.get_running_loop().stop()
  946. ws_client_module.Client._receive_message_loop = _receive_message_loop_exit_notify
  947. _WS_ISOLATION_INSTALLED = True
  948. def _run_official_feishu_ws_client(ws_client: Any, adapter: Any) -> None:
  949. """Run the official Lark WS client in its own thread-local loop (see isolation notes above)."""
  950. import lark_oapi.ws.client as ws_client_module
  951. loop = asyncio.new_event_loop()
  952. asyncio.set_event_loop(loop)
  953. adapter._ws_thread_loop = loop
  954. original_configure = getattr(ws_client, "_configure", None)
  955. def _apply_runtime_ws_overrides() -> None:
  956. try:
  957. ws_client._reconnect_nonce = adapter._ws_reconnect_nonce
  958. ws_client._reconnect_interval = adapter._ws_reconnect_interval
  959. if adapter._ws_ping_interval is not None:
  960. ws_client._ping_interval = adapter._ws_ping_interval
  961. # SDK observer (lark-oapi ``Client.on_reconnecting``, fired first thing in ``_reconnect()``):
  962. # on the live link ``_auto_reconnect`` is on, so the ladder runs *inside* the receive loop
  963. # and the thread never dies — without this the supervisor's ``retrying`` is never published.
  964. ws_client.on_reconnecting = _on_reconnecting
  965. except Exception:
  966. logger.debug("[Feishu] Failed to apply websocket runtime overrides", exc_info=True)
  967. connect_overrides = {
  968. key: value
  969. for key, value in (("ping_interval", adapter._ws_ping_interval), ("ping_timeout", adapter._ws_ping_timeout))
  970. if value is not None
  971. }
  972. adapter_loop = adapter._loop
  973. def _on_reconnecting() -> None:
  974. if adapter_loop is not None and not adapter_loop.is_closed():
  975. adapter_loop.call_soon_threadsafe(adapter._ws_link_retrying, ws_client)
  976. def _on_link_up() -> None:
  977. # Fired on the WS thread when the SDK scheduled a receive loop (handshake done); hop to the
  978. # adapter loop so the ``connected`` re-stamp after a supervisor rebuild runs where the adapter's
  979. # state lives.
  980. if adapter_loop is not None and not adapter_loop.is_closed():
  981. adapter_loop.call_soon_threadsafe(adapter._ws_link_up, ws_client)
  982. _install_lark_ws_isolation(ws_client_module)
  983. _ws_isolation_state.loop = loop
  984. _ws_isolation_state.connect_kwargs = connect_overrides
  985. _ws_isolation_state.on_link_up = _on_link_up
  986. _ws_isolation_state.adapter = adapter
  987. def _configure_with_overrides(conf: Any) -> Any:
  988. if original_configure is None:
  989. raise RuntimeError("Feishu _configure_with_overrides called but original_configure is None")
  990. result = original_configure(conf)
  991. _apply_runtime_ws_overrides()
  992. return result
  993. if original_configure is not None:
  994. ws_client._configure = _configure_with_overrides
  995. _apply_runtime_ws_overrides()
  996. try:
  997. ws_client.start()
  998. except Exception:
  999. pass
  1000. finally:
  1001. _ws_isolation_state.loop = None
  1002. _ws_isolation_state.connect_kwargs = None
  1003. _ws_isolation_state.on_link_up = None
  1004. _ws_isolation_state.adapter = None
  1005. if original_configure is not None:
  1006. ws_client._configure = original_configure
  1007. pending = [t for t in asyncio.all_tasks(loop) if not t.done()]
  1008. for task in pending:
  1009. task.cancel()
  1010. if pending:
  1011. loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
  1012. for closer in (loop.stop, loop.close):
  1013. try:
  1014. closer()
  1015. except Exception:
  1016. pass
  1017. adapter._ws_thread_loop = None
  1018. def _load_lark_oapi() -> bool:
  1019. """Import and bind the Feishu SDK after an explicit connection request."""
  1020. if FEISHU_AVAILABLE:
  1021. return True
  1022. with _lark_import_lock:
  1023. if FEISHU_AVAILABLE:
  1024. return True
  1025. import importlib
  1026. try:
  1027. bound: dict[str, Any] = {"lark": importlib.import_module("lark_oapi")}
  1028. for module_name, names in _LARK_SDK_IMPORTS:
  1029. module = importlib.import_module(module_name)
  1030. bound.update({name: getattr(module, name) for name in names})
  1031. bound["FeishuWSClient"] = importlib.import_module("lark_oapi.ws").Client
  1032. except (ImportError, AttributeError):
  1033. return False
  1034. bound["FEISHU_AVAILABLE"] = True
  1035. globals().update(bound)
  1036. return True
  1037. def feishu_deps_present() -> bool:
  1038. """PASSIVE registry ``check_fn``: is lark-oapi installed? Must never install or import the SDK.
  1039. Uses cheap importlib.metadata lookups; the real import is deferred to ``_load_lark_oapi``
  1040. and the ACTIVE installer is ``check_feishu_requirements`` (``ensure_deps_fn``).
  1041. Registry ``check_fn`` — called from status displays and config loading, so it must never install
  1042. anything. The ACTIVE lazy-installer (``check_feishu_requirements``) is registered as ``ensure_deps_fn``
  1043. and runs from ``create_adapter()`` when this returns False (#79812).
  1044. """
  1045. if FEISHU_AVAILABLE:
  1046. return True
  1047. try:
  1048. from pm.extras import available
  1049. return available("feishu")
  1050. except Exception: # pragma: no cover — defensive
  1051. return False
  1052. def check_feishu_requirements() -> bool:
  1053. """Ensure Feishu dependencies are installed without importing the SDK."""
  1054. if FEISHU_AVAILABLE:
  1055. return True
  1056. from pm import ensure_import
  1057. try:
  1058. ensure_import("feishu")
  1059. return True
  1060. except Exception:
  1061. return False
  1062. def _tenant_get_request(uri: str, *, queries: Optional[list[tuple[str, str]]] = None) -> Any:
  1063. """Raw ``BaseRequest`` GET with the tenant access token (bot/v3 endpoints have no typed SDK request)."""
  1064. builder = BaseRequest.builder().http_method(HttpMethod.GET).uri(uri)
  1065. if queries is not None:
  1066. builder = builder.queries(queries)
  1067. return builder.token_types({AccessTokenType.TENANT}).build()
  1068. def _sdk_domain(domain_name: str) -> Any:
  1069. return LARK_DOMAIN if domain_name == "lark" else FEISHU_DOMAIN
  1070. def _build_lark_client(app_id: str, app_secret: str, sdk_domain: Any) -> Any:
  1071. return lark.Client.builder().app_id(app_id).app_secret(app_secret).domain(sdk_domain).log_level(lark.LogLevel.WARNING).build()
  1072. def _card_button(label: str, btn_type: str, value: dict[str, Any]) -> dict[str, Any]:
  1073. return {"tag": "button", "text": {"tag": "plain_text", "content": label}, "type": btn_type, "value": value}
  1074. def _card(title: str, template: str, markdown: str, *, actions: Optional[list[dict[str, Any]]] = None) -> dict[str, Any]:
  1075. """Wide interactive card: colored header + one markdown block (+ an optional button row)."""
  1076. elements: list[dict[str, Any]] = [{"tag": "markdown", "content": markdown}]
  1077. if actions is not None:
  1078. elements.append({"tag": "action", "actions": actions})
  1079. return {
  1080. "config": {"wide_screen_mode": True},
  1081. "header": {"title": {"content": title, "tag": "plain_text"}, "template": template},
  1082. "elements": elements,
  1083. }
  1084. def _sdk_build(request_cls: Any, **fields: Any) -> Any:
  1085. """``request_cls.builder().<field>(value)...build()``; SimpleNamespace when the SDK is unbound."""
  1086. if request_cls is None:
  1087. return SimpleNamespace(**fields)
  1088. builder = request_cls.builder()
  1089. for name, value in fields.items():
  1090. builder = getattr(builder, name)(value)
  1091. return builder.build()
  1092. class FeishuAdapter(FeishuChoiceCardsMixin, BasePlatformAdapter):
  1093. """Feishu/Lark bot adapter."""
  1094. # Answers /p/<profile>/... on the default listener for a served secondary (shared_ingress).
  1095. serves_profile_prefix: bool = True
  1096. supports_code_blocks = True # Feishu renders fenced code blocks
  1097. splits_long_messages = True # send() chunks via truncate_message(MAX_MESSAGE_LENGTH)
  1098. serial_receive_loop = True # a chat's next message waits on its lock (_handle_message_with_guards)
  1099. MAX_MESSAGE_LENGTH = 8000
  1100. CHAT_LOCK_MAX_SIZE: int = 1000 # distinct chat IDs kept in _chat_locks before LRU eviction
  1101. _SPLIT_THRESHOLD = 4000 # chunk near Feishu's ~4096-char client split → continuation almost certain
  1102. # --- Lifecycle — init / settings / connect / disconnect ---
  1103. def __init__(self, config: PlatformConfig):
  1104. super().__init__(config, Platform.FEISHU)
  1105. self._settings = self._load_settings(config.extra or {})
  1106. self._apply_settings(self._settings)
  1107. self._client: Optional[Any] = None
  1108. # Adapter-owned pool for blocking SDK calls, recreated on demand: a torn-down default
  1109. # executor can no longer wedge sends with "Executor shutdown has been called".
  1110. # See issue #10849.
  1111. self._sdk_executor_lock = threading.Lock()
  1112. self._sdk_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
  1113. self._sdk_executor_closing = False # set on disconnect so a real teardown isn't resurrected
  1114. self._ws_client = self._ws_future = self._ws_supervisor = self._ws_thread_loop = None
  1115. self._ws_restart_backoff = 5.0
  1116. self._loop: Optional[asyncio.AbstractEventLoop] = None
  1117. self._webhook_runner = self._webhook_site = self._event_handler = None
  1118. self._seen_message_ids: dict[str, float] = {} # message_id → seen_at (time.time())
  1119. self._seen_message_order: list[str] = []
  1120. self._dedup_state_path = get_hermes_home() / "feishu_seen_message_ids.json"
  1121. self._dedup_lock = threading.Lock()
  1122. # Serializes the offloaded dedup-state flushes so two concurrent
  1123. # inbound messages cannot land their writes out of order.
  1124. self._dedup_persist_lock = asyncio.Lock()
  1125. self._sender_name_cache: dict[str, tuple[str, float]] = {} # sender_id → (name, expire_at)
  1126. self._webhook_rate_counts: dict[str, tuple[int, float]] = {} # rate_key → (count, window_start)
  1127. self._webhook_anomaly_counts: dict[str, tuple[int, str, float]] = {} # ip → (count, last_status, first_seen)
  1128. self._card_action_tokens: dict[str, float] = {} # token → first_seen_time
  1129. # Inbound events that arrived before the loop was ready; one drainer thread replays them.
  1130. self._pending_inbound_events: list[Any] = []
  1131. self._pending_inbound_lock = threading.Lock()
  1132. self._pending_drain_scheduled = False
  1133. self._pending_inbound_max_depth = 1000 # cap queue; drop oldest beyond
  1134. self._chat_locks: collections.OrderedDict[str, asyncio.Lock] = collections.OrderedDict() # chat_id → lock (per-chat serial processing, LRU-bounded)
  1135. self._chat_info_cache: dict[str, dict[str, Any]] = {}
  1136. self._message_text_cache: OrderedDict[str, Optional[str]] = OrderedDict()
  1137. self._app_lock_identity: Optional[str] = None
  1138. self._text_batch_state = FeishuBatchState()
  1139. self._pending_text_batches = self._text_batch_state.events
  1140. self._pending_text_batch_tasks = self._text_batch_state.tasks
  1141. self._pending_text_batch_counts = self._text_batch_state.counts
  1142. self._media_batch_state = FeishuBatchState()
  1143. self._pending_media_batches = self._media_batch_state.events
  1144. self._pending_media_batch_tasks = self._media_batch_state.tasks
  1145. # Button-card state: id → {session_key, message_id, chat_id}
  1146. self._approval_state: dict[int, dict[str, str]] = {}
  1147. self._approval_counter = itertools.count(1)
  1148. self._update_prompt_state: dict[int, dict[str, str]] = {}
  1149. self._update_prompt_counter = itertools.count(1)
  1150. self._init_choice_card_state()
  1151. # Reaction deletion needs the opaque reaction_id from create, cached per message_id.
  1152. self._pending_processing_reactions: OrderedDict[str, str] = OrderedDict()
  1153. self._load_seen_message_ids()
  1154. @staticmethod
  1155. def _load_settings(extra: dict[str, Any]) -> FeishuAdapterSettings:
  1156. def _id_set(values: Any) -> set[str]:
  1157. return {str(u).strip() for u in values if str(u).strip()}
  1158. def _secret(name: str, default: str = "") -> str:
  1159. return _get_scoped_secret(name, default).strip()
  1160. def _extra_or_secret(key: str, env: str, default: str = "") -> str:
  1161. return str(_shared_extra_or_secret(extra, key, env, default)).strip()
  1162. _extra_or_env = _extra_or_secret
  1163. raw_group_rules = extra.get("group_rules", {})
  1164. group_rules: dict[str, FeishuGroupRule] = {}
  1165. if isinstance(raw_group_rules, dict):
  1166. for chat_id, rule_cfg in raw_group_rules.items():
  1167. if not isinstance(rule_cfg, dict):
  1168. continue
  1169. group_rules[str(chat_id)] = FeishuGroupRule(
  1170. policy=str(rule_cfg.get("policy", "open")).strip().lower(),
  1171. allowlist=_id_set(rule_cfg.get("allowlist", [])),
  1172. blacklist=_id_set(rule_cfg.get("blacklist", [])),
  1173. # Only override when explicitly set — missing vs false must not collapse.
  1174. require_mention=_to_boolean(rule_cfg["require_mention"]) if "require_mention" in rule_cfg else None,
  1175. )
  1176. # Scoped read: under multiplex a secondary profile's .env must govern its own adapter; yaml
  1177. # feishu.allow_bots reaches it via ``extra`` (the env bridge is skipped under its scope).
  1178. # See #86905.
  1179. allow_bots = str(_extra_or_secret("allow_bots", "FEISHU_ALLOW_BOTS", "none") or "none").strip().lower()
  1180. if allow_bots not in {"none", "mentions", "all"}:
  1181. logger.warning(
  1182. "[Feishu] Unknown allow_bots=%r, falling back to 'none'. Valid: none, mentions, all.",
  1183. allow_bots,
  1184. )
  1185. allow_bots = "none"
  1186. allow_all_dm = any(
  1187. _secret(var).lower() in {"true", "1", "yes"} for var in ("FEISHU_ALLOW_ALL_USERS", "GATEWAY_ALLOW_ALL_USERS")
  1188. )
  1189. return FeishuAdapterSettings(
  1190. app_id=_extra_or_secret("app_id", "FEISHU_APP_ID"),
  1191. app_secret=_extra_or_secret("app_secret", "FEISHU_APP_SECRET"),
  1192. domain_name=_extra_or_env("domain", "FEISHU_DOMAIN", "feishu").lower(),
  1193. connection_mode=_extra_or_env("connection_mode", "FEISHU_CONNECTION_MODE", "websocket").lower(),
  1194. encrypt_key=_extra_or_secret("encrypt_key", "FEISHU_ENCRYPT_KEY"),
  1195. verification_token=_extra_or_secret("verification_token", "FEISHU_VERIFICATION_TOKEN"),
  1196. group_policy=_secret("FEISHU_GROUP_POLICY", "allowlist").lower(),
  1197. allowed_group_users=frozenset(_id_set(_get_scoped_secret("FEISHU_ALLOWED_USERS", "").split(","))),
  1198. bot_open_id=_secret("FEISHU_BOT_OPEN_ID"),
  1199. bot_user_id=_secret("FEISHU_BOT_USER_ID"),
  1200. bot_name=_secret("FEISHU_BOT_NAME"),
  1201. dedup_cache_size=max(32, env_int("HERMES_FEISHU_DEDUP_CACHE_SIZE", _DEFAULT_DEDUP_CACHE_SIZE)),
  1202. text_batch_delay_seconds=env_float("HERMES_FEISHU_TEXT_BATCH_DELAY_SECONDS", _DEFAULT_TEXT_BATCH_DELAY_SECONDS),
  1203. text_batch_split_delay_seconds=env_float("HERMES_FEISHU_TEXT_BATCH_SPLIT_DELAY_SECONDS", 2.0),
  1204. text_batch_max_messages=max(1, env_int("HERMES_FEISHU_TEXT_BATCH_MAX_MESSAGES", _DEFAULT_TEXT_BATCH_MAX_MESSAGES)),
  1205. text_batch_max_chars=max(1, env_int("HERMES_FEISHU_TEXT_BATCH_MAX_CHARS", _DEFAULT_TEXT_BATCH_MAX_CHARS)),
  1206. media_batch_delay_seconds=env_float("HERMES_FEISHU_MEDIA_BATCH_DELAY_SECONDS", _DEFAULT_MEDIA_BATCH_DELAY_SECONDS),
  1207. webhook_host=_extra_or_env("webhook_host", "FEISHU_WEBHOOK_HOST", _DEFAULT_WEBHOOK_HOST),
  1208. webhook_port=int(extra.get("webhook_port") or _get_scoped_secret("FEISHU_WEBHOOK_PORT", str(_DEFAULT_WEBHOOK_PORT))),
  1209. webhook_path=_extra_or_env("webhook_path", "FEISHU_WEBHOOK_PATH", _DEFAULT_WEBHOOK_PATH) or _DEFAULT_WEBHOOK_PATH,
  1210. ws_reconnect_nonce=_coerce_required_int(extra.get("ws_reconnect_nonce"), default=30, min_value=0),
  1211. ws_reconnect_interval=_coerce_required_int(extra.get("ws_reconnect_interval"), default=120, min_value=1),
  1212. ws_ping_interval=_coerce_int(extra.get("ws_ping_interval"), default=None, min_value=1),
  1213. ws_ping_timeout=_coerce_int(extra.get("ws_ping_timeout"), default=None, min_value=1),
  1214. admins=frozenset(_id_set(extra.get("admins", []))),
  1215. default_group_policy=str(extra.get("default_group_policy", "")).strip().lower(),
  1216. group_rules=group_rules, allow_bots=allow_bots, allow_all_dm=allow_all_dm,
  1217. require_mention=_to_boolean(extra.get("require_mention", _get_scoped_secret("FEISHU_REQUIRE_MENTION", "true"))),
  1218. )
  1219. def _apply_settings(self, settings: FeishuAdapterSettings) -> None:
  1220. # Every settings field is mirrored as ``self._<field>``; the three below need coercion.
  1221. for name in FeishuAdapterSettings.__dataclass_fields__:
  1222. setattr(self, f"_{name}", getattr(settings, name))
  1223. self._allowed_group_users = set(settings.allowed_group_users)
  1224. self._admins = set(settings.admins)
  1225. self._default_group_policy = settings.default_group_policy or settings.group_policy
  1226. def _build_event_handler(self) -> Any:
  1227. if EventDispatcherHandler is None:
  1228. return None
  1229. return (
  1230. EventDispatcherHandler.builder(self._encrypt_key, self._verification_token)
  1231. .register_p2_im_message_message_read_v1(self._on_message_read_event)
  1232. .register_p2_im_message_receive_v1(self._on_message_event)
  1233. .register_p2_im_message_reaction_created_v1(lambda d: self._on_reaction_event("im.message.reaction.created_v1", d))
  1234. .register_p2_im_message_reaction_deleted_v1(lambda d: self._on_reaction_event("im.message.reaction.deleted_v1", d))
  1235. .register_p2_card_action_trigger(self._on_card_action_trigger)
  1236. .register_p2_im_chat_member_bot_added_v1(self._on_bot_added_to_chat)
  1237. .register_p2_im_chat_member_bot_deleted_v1(self._on_bot_removed_from_chat)
  1238. .register_p2_im_chat_access_event_bot_p2p_chat_entered_v1(self._on_p2p_chat_entered)
  1239. .register_p2_im_message_recalled_v1(self._on_message_recalled)
  1240. .register_p2_customized_event("drive.notice.comment_add_v1", self._on_drive_comment_event)
  1241. .register_p2_customized_event("vc.bot.meeting_invited_v1", self._on_meeting_invited_event)
  1242. .build()
  1243. )
  1244. def _get_sdk_executor(self) -> concurrent.futures.ThreadPoolExecutor:
  1245. """Adapter-owned executor; recreated after an *external* shutdown, never after our own close.
  1246. Recreates the pool if it was never built or was shut down by an *external* teardown of the loop's
  1247. default executor, so that can no longer permanently wedge sends (#10849). Refuses to resurrect once
  1248. the adapter itself is closing — a real disconnect/shutdown stays shut.
  1249. """
  1250. lock = getattr(self, "_sdk_executor_lock", None) # bare adapters (tests) may lack __init__ state
  1251. if lock is None:
  1252. lock = self._sdk_executor_lock = threading.Lock()
  1253. with lock:
  1254. if getattr(self, "_sdk_executor_closing", False):
  1255. raise RuntimeError("Feishu adapter is shutting down; SDK executor unavailable")
  1256. executor = getattr(self, "_sdk_executor", None)
  1257. if executor is None or getattr(executor, "_shutdown", False):
  1258. executor = concurrent.futures.ThreadPoolExecutor(max_workers=10, thread_name_prefix="hermes-feishu-sdk")
  1259. self._sdk_executor = executor
  1260. return executor
  1261. async def _run_blocking(self, func, *args):
  1262. """Run a blocking Feishu SDK call on the adapter-owned thread pool.
  1263. ``copy_context().run`` mirrors ``asyncio.to_thread``: the worker sees the caller's
  1264. profile HERMES_HOME override / secret scope (multiplexed dedup flush, thread lookup).
  1265. """
  1266. loop = asyncio.get_running_loop()
  1267. return await loop.run_in_executor(
  1268. self._get_sdk_executor(), contextvars.copy_context().run, func, *args)
  1269. def _shutdown_sdk_executor(self) -> None:
  1270. """Stop the adapter-owned SDK executor without touching the loop default."""
  1271. lock = getattr(self, "_sdk_executor_lock", None)
  1272. if lock is None:
  1273. return
  1274. with lock:
  1275. self._sdk_executor_closing = True
  1276. executor = getattr(self, "_sdk_executor", None)
  1277. self._sdk_executor = None
  1278. if executor is None:
  1279. return
  1280. try:
  1281. executor.shutdown(wait=False, cancel_futures=True)
  1282. except TypeError:
  1283. executor.shutdown(wait=False)
  1284. async def connect(self, *, is_reconnect: bool = False) -> bool:
  1285. """Connect to Feishu/Lark."""
  1286. self._sdk_executor_closing = False # re-arm the SDK executor after a prior disconnect
  1287. if not self._app_id or not self._app_secret:
  1288. logger.error("[Feishu] FEISHU_APP_ID or FEISHU_APP_SECRET not set")
  1289. return False
  1290. if self._connection_mode not in {"websocket", "webhook"}:
  1291. logger.error(
  1292. "[Feishu] Unsupported FEISHU_CONNECTION_MODE=%s. Supported modes: websocket, webhook.",
  1293. self._connection_mode,
  1294. )
  1295. return False
  1296. if self._connection_mode == "webhook" and not (self._verification_token or self._encrypt_key):
  1297. logger.error("[Feishu] Webhook mode requires FEISHU_VERIFICATION_TOKEN or FEISHU_ENCRYPT_KEY.")
  1298. return False
  1299. if not await asyncio.to_thread(_load_lark_oapi):
  1300. logger.error("[Feishu] lark-oapi not installed")
  1301. return False
  1302. try:
  1303. self._app_lock_identity = self._app_id
  1304. acquired, existing = acquire_scoped_lock(
  1305. _FEISHU_APP_LOCK_SCOPE, self._app_lock_identity, metadata={"platform": self.platform.value},
  1306. )
  1307. if not acquired:
  1308. owner_pid = existing.get("pid") if isinstance(existing, dict) else None
  1309. message = (
  1310. "Another local Hermes gateway is already using this Feishu app_id"
  1311. + (f" (PID {owner_pid})." if owner_pid else ".")
  1312. + " Stop the other gateway before starting a second Feishu websocket client."
  1313. )
  1314. logger.error("[Feishu] %s", message)
  1315. self._set_fatal_error("feishu_app_lock", message, retryable=False)
  1316. return False
  1317. self._loop = asyncio.get_running_loop()
  1318. await self._connect_with_retry()
  1319. if self._connection_mode == "websocket":
  1320. # The WS thread can die without any external signal; keep a watcher alive.
  1321. self._ws_supervisor = asyncio.ensure_future(self._supervise_websocket_thread())
  1322. self._mark_connected()
  1323. logger.info("[Feishu] Connected in %s mode (%s)", self._connection_mode, self._domain_name)
  1324. # Plugin-registered native handlers (lark_oapi client).
  1325. self._wire_plugin_handlers(self._client)
  1326. return True
  1327. except Exception as exc:
  1328. await self._release_app_lock()
  1329. message = f"Feishu startup failed: {exc}"
  1330. self._set_fatal_error("feishu_connect_error", message, retryable=True)
  1331. logger.error("[Feishu] Failed to connect: %s", exc, exc_info=True)
  1332. return False
  1333. async def disconnect(self) -> None:
  1334. """Disconnect from Feishu/Lark."""
  1335. self._running = False
  1336. if self._ws_supervisor is not None:
  1337. self._ws_supervisor.cancel()
  1338. self._ws_supervisor = None
  1339. await self._cancel_pending_tasks(self._pending_text_batch_tasks)
  1340. await self._cancel_pending_tasks(self._pending_media_batch_tasks)
  1341. self._reset_batch_buffers()
  1342. # ``_disable_websocket_auto_reconnect()`` nils ``_ws_client`` — capture first.
  1343. # Send a WebSocket CLOSE frame to Feishu BEFORE tearing down the thread loop. Without this, Feishu's
  1344. # server never learns the connection is dead and continues routing messages to the stale endpoint —
  1345. # the channel goes silent until the server-side CLOSE-WAIT expires (minutes to hours). See issue
  1346. # #10202.
  1347. ws_client = self._ws_client
  1348. ws_thread_loop = self._ws_thread_loop
  1349. self._disable_websocket_auto_reconnect()
  1350. await self._stop_webhook_server()
  1351. await self._teardown_ws_thread(ws_client, ws_thread_loop)
  1352. self._ws_future = None
  1353. self._ws_thread_loop = None
  1354. self._loop = None
  1355. self._event_handler = None
  1356. self._shutdown_sdk_executor()
  1357. self._persist_seen_message_ids()
  1358. await self._release_app_lock()
  1359. self._mark_disconnected()
  1360. logger.info("[Feishu] Disconnected")
  1361. async def _teardown_ws_thread(self, ws_client: Any, ws_thread_loop: Any) -> None:
  1362. """CLOSE frame → cancel the WS thread's tasks → wait for the thread future."""
  1363. # Send the CLOSE frame BEFORE tearing down the thread loop; otherwise Feishu keeps
  1364. # routing to the stale endpoint until server-side CLOSE-WAIT expires (minutes to hours).
  1365. loop_alive = ws_thread_loop is not None and not ws_thread_loop.is_closed()
  1366. if ws_client is not None and loop_alive and hasattr(ws_client, "_disconnect"):
  1367. try:
  1368. future = asyncio.run_coroutine_threadsafe(ws_client._disconnect(), ws_thread_loop)
  1369. # A CLOSE frame is one control frame; if 5s isn't enough the link is already wedged.
  1370. await asyncio.wait_for(asyncio.wrap_future(future), timeout=5.0)
  1371. logger.debug("[Feishu] Sent WebSocket CLOSE frame to Feishu")
  1372. except TimeoutError:
  1373. logger.warning(
  1374. "[Feishu] CLOSE frame not acknowledged within 5s — "
  1375. "Feishu may briefly route messages to the stale "
  1376. "connection until server-side timeout"
  1377. )
  1378. except Exception as exc:
  1379. logger.debug("[Feishu] Could not send WebSocket CLOSE frame: %s", exc, exc_info=True)
  1380. if loop_alive:
  1381. logger.debug("[Feishu] Cancelling websocket thread tasks and stopping loop")
  1382. def cancel_all_tasks() -> None:
  1383. tasks = [t for t in asyncio.all_tasks(ws_thread_loop) if not t.done()]
  1384. logger.debug("[Feishu] Found %d pending tasks in websocket thread", len(tasks))
  1385. for task in tasks:
  1386. task.cancel()
  1387. ws_thread_loop.call_later(0.1, ws_thread_loop.stop)
  1388. ws_thread_loop.call_soon_threadsafe(cancel_all_tasks)
  1389. ws_future = self._ws_future
  1390. if ws_future is not None:
  1391. try:
  1392. logger.debug("[Feishu] Waiting for websocket thread to exit (timeout=10s)")
  1393. await asyncio.wait_for(asyncio.shield(ws_future), timeout=10.0)
  1394. logger.debug("[Feishu] Websocket thread exited cleanly")
  1395. except TimeoutError:
  1396. logger.warning("[Feishu] Websocket thread did not exit within 10s - may be stuck")
  1397. except asyncio.CancelledError:
  1398. logger.debug("[Feishu] Websocket thread cancelled during disconnect")
  1399. except Exception as exc:
  1400. logger.debug("[Feishu] Websocket thread exited with error: %s", exc, exc_info=True)
  1401. async def _cancel_pending_tasks(self, tasks: dict[str, asyncio.Task]) -> None:
  1402. pending = [task for task in tasks.values() if task and not task.done()]
  1403. for task in pending:
  1404. task.cancel()
  1405. if pending:
  1406. await asyncio.gather(*pending, return_exceptions=True)
  1407. tasks.clear()
  1408. def _reset_batch_buffers(self) -> None:
  1409. self._pending_text_batches.clear()
  1410. self._pending_text_batch_counts.clear()
  1411. self._pending_media_batches.clear()
  1412. def _disable_websocket_auto_reconnect(self) -> None:
  1413. if self._ws_client is None:
  1414. return
  1415. try:
  1416. self._ws_client._auto_reconnect = False
  1417. except Exception:
  1418. pass
  1419. finally:
  1420. self._ws_client = None
  1421. async def _stop_webhook_server(self) -> None:
  1422. if self._webhook_runner is None:
  1423. return
  1424. try:
  1425. await self._webhook_runner.cleanup()
  1426. finally:
  1427. self._webhook_runner = None
  1428. self._webhook_site = None
  1429. # --- Outbound — send / edit / send_image / send_voice / … ---
  1430. async def send(
  1431. self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None,
  1432. ) -> SendResult:
  1433. """Send a Feishu message."""
  1434. if not self._client:
  1435. return SendResult(success=False, error="Not connected")
  1436. formatted = self.format_message(content)
  1437. chunks = self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
  1438. # Decide markdown-vs-text once for the whole message: a chunk of a long
  1439. # markdown reply may be plain prose that fails the per-chunk regex and would
  1440. # otherwise render as literal ``**bold`` / fences while other chunks render.
  1441. # Lock the markdown decision at the whole-message level so every chunk consistently uses ``post``.
  1442. # See #26841.
  1443. prefer_post = bool(_MARKDOWN_HINT_RE.search(formatted))
  1444. last_response = None
  1445. async def _send_plain(chunk: str) -> Any:
  1446. return await self._feishu_send_with_retry(
  1447. chat_id=chat_id,
  1448. msg_type="text",
  1449. payload=json.dumps({"text": _strip_markdown_to_plain_text(chunk)}, ensure_ascii=False),
  1450. reply_to=reply_to,
  1451. metadata=metadata,
  1452. )
  1453. try:
  1454. for chunk in chunks:
  1455. msg_type, payload = self._build_outbound_payload(chunk, prefer_post=prefer_post)
  1456. try:
  1457. response = await self._feishu_send_with_retry(
  1458. chat_id=chat_id, msg_type=msg_type, payload=payload, reply_to=reply_to, metadata=metadata,
  1459. )
  1460. except Exception as exc:
  1461. if msg_type != "post" or not _POST_CONTENT_INVALID_RE.search(str(exc)):
  1462. raise
  1463. logger.warning("[Feishu] Invalid post payload rejected by API; falling back to plain text")
  1464. response = await _send_plain(chunk)
  1465. if (
  1466. msg_type == "post"
  1467. and not self._response_succeeded(response)
  1468. and _POST_CONTENT_INVALID_RE.search(str(getattr(response, "msg", "") or ""))
  1469. ):
  1470. logger.warning("[Feishu] Post payload rejected by API response; falling back to plain text")
  1471. response = await _send_plain(chunk)
  1472. last_response = response
  1473. return self._finalize_send_result(last_response, "send failed")
  1474. except Exception as exc:
  1475. logger.error("[Feishu] Send error: %s", exc, exc_info=True)
  1476. return SendResult(success=False, error=str(exc))
  1477. async def edit_message(self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult:
  1478. """Edit a previously sent Feishu text/post message."""
  1479. if not self._client:
  1480. return SendResult(success=False, error="Not connected")
  1481. content = self.format_message(content)
  1482. async def _update(msg_type: str, payload: str) -> SendResult:
  1483. body = self._build_update_message_body(msg_type=msg_type, content=payload)
  1484. request = self._build_update_message_request(message_id=message_id, request_body=body)
  1485. response = await self._run_blocking(self._client.im.v1.message.update, request)
  1486. return self._finalize_send_result(response, "update failed")
  1487. try:
  1488. msg_type, payload = self._build_outbound_payload(content)
  1489. result = await _update(msg_type, payload)
  1490. if not result.success and msg_type == "post" and _POST_CONTENT_INVALID_RE.search(result.error or ""):
  1491. logger.warning("[Feishu] Invalid post update payload rejected by API; falling back to plain text")
  1492. result = await _update(
  1493. "text", json.dumps({"text": _strip_markdown_to_plain_text(content)}, ensure_ascii=False),
  1494. )
  1495. if result.success:
  1496. result.message_id = message_id
  1497. return result
  1498. except Exception as exc:
  1499. logger.error("[Feishu] Failed to edit message %s: %s", message_id, exc, exc_info=True)
  1500. return SendResult(success=False, error=str(exc))
  1501. async def delete_message(self, chat_id: str, message_id: str) -> bool:
  1502. """Delete a bot-posted message (used by stream-consumer preview cleanup)."""
  1503. if not self._client or not message_id:
  1504. return False
  1505. try:
  1506. request = self._build_delete_message_request(message_id)
  1507. response = await self._run_blocking(self._client.im.v1.message.delete, request)
  1508. if self._response_succeeded(response):
  1509. return True
  1510. logger.debug(
  1511. "[Feishu] Delete of message %s rejected: code=%s msg=%s",
  1512. message_id, getattr(response, "code", None), getattr(response, "msg", None),
  1513. )
  1514. return False
  1515. except Exception:
  1516. logger.debug("[Feishu] Failed to delete message %s", message_id, exc_info=True)
  1517. return False
  1518. # Template attrs for the shared _format_exec_approval core. The card
  1519. # header carries the title, so the text core starts at the code fence.
  1520. _EA_HEADER = ""
  1521. _EA_CMD_BUDGET = 3000
  1522. # Resolved per call (not at class-body time) so the active language applies.
  1523. @property
  1524. def _EA_REASON_LABEL(self) -> str:
  1525. return f"**{t('gateway.exec_approval.reason_label')}:** "
  1526. @property
  1527. def _EA_SMART_DENY_LINE(self) -> str:
  1528. line = t("gateway.exec_approval.smart_deny_line")
  1529. label, sep, rest = line.partition(":")
  1530. return "\n\n" + (f"**{label}{sep}**{rest}" if sep else line)
  1531. @property
  1532. def _EA_ACTION_LABELS(self) -> dict[str, str]:
  1533. return {"once": "✅ " + t("gateway.exec_approval.action_once"),
  1534. "session": "✅ " + t("platform.feishu.approval.action_session"),
  1535. "always": "✅ " + t("platform.feishu.approval.action_always"),
  1536. "deny": "❌ " + t("gateway.exec_approval.action_deny")}
  1537. _EA_CARD_ACTIONS = {"once": "approve_once", "session": "approve_session", "always": "approve_always", "deny": "deny"}
  1538. async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:
  1539. """Approval-button card; ``hermes_action`` in each button value lets the click callback
  1540. route to ``resolve_gateway_approval()`` and unblock the waiting agent thread."""
  1541. if not self._client:
  1542. return SendResult(success=False, error="Not connected")
  1543. try:
  1544. approval_id = next(self._approval_counter)
  1545. actions = [
  1546. _card_button(label, style or "default",
  1547. {"hermes_action": self._EA_CARD_ACTIONS[choice], "approval_id": approval_id})
  1548. for label, choice, style in prompt.actions]
  1549. card = _card(f"⚠️ {t('gateway.exec_approval.header')}", "orange", prompt.text, actions=actions)
  1550. return await self._send_interactive_card(
  1551. prompt.chat_id, card, prompt.metadata, "send_exec_approval failed",
  1552. state_map=self._approval_state, state_id=approval_id, session_key=prompt.session_key,
  1553. extra_state={"body": prompt.text.replace(self._ea_deadline_line(), ""), # deadline is moot once resolved
  1554. "request_id": prompt.request_id or ""},
  1555. )
  1556. except Exception as exc:
  1557. logger.warning("[Feishu] send_exec_approval failed: %s", exc)
  1558. return SendResult(success=False, error=str(exc))
  1559. async def _send_interactive_card(
  1560. self, chat_id: str, card: dict[str, Any], metadata: Optional[dict[str, Any]], failure_message: str, *,
  1561. state_map: dict[int, dict[str, str]], state_id: int, session_key: str, extra_state: Optional[dict[str, str]] = None,
  1562. ) -> SendResult:
  1563. """Send a button card and, on success, remember where it went (plus *extra_state*) so a click can be validated."""
  1564. response = await self._feishu_send_with_retry(
  1565. chat_id=chat_id, msg_type="interactive", payload=json.dumps(card, ensure_ascii=False),
  1566. reply_to=None, metadata=metadata,
  1567. )
  1568. result = self._finalize_send_result(response, failure_message)
  1569. if result.success:
  1570. state_map[state_id] = {
  1571. "session_key": session_key,
  1572. "message_id": result.message_id or "",
  1573. "chat_id": chat_id,
  1574. **(extra_state or {}),
  1575. }
  1576. return result
  1577. @staticmethod
  1578. def _build_update_prompt_card(*, prompt: str, default: str, prompt_id: int) -> dict[str, Any]:
  1579. default_hint = t("platform.feishu.update_prompt.default_hint", default=default) if default else ""
  1580. def _btn(label: str, answer: str, btn_type: str) -> dict:
  1581. return _card_button(label, btn_type, {"hermes_update_prompt_action": answer, "update_prompt_id": prompt_id})
  1582. actions = [_btn(t("platform.feishu.update_prompt.answer_yes"), "y", "primary"),
  1583. _btn(t("platform.feishu.update_prompt.answer_no"), "n", "danger")]
  1584. return _card(t("platform.feishu.update_prompt.title"), "orange", f"{prompt}{default_hint}", actions=actions)
  1585. async def send_update_prompt(
  1586. self, chat_id: str, prompt: str, default: str = "", session_key: str = "",
  1587. metadata: Optional[dict[str, Any]] = None,
  1588. ) -> SendResult:
  1589. """Send an interactive update prompt with Yes/No buttons."""
  1590. if not self._client:
  1591. return SendResult(success=False, error="Not connected")
  1592. try:
  1593. prompt_id = next(self._update_prompt_counter)
  1594. card = self._build_update_prompt_card(prompt=prompt, default=default, prompt_id=prompt_id)
  1595. return await self._send_interactive_card(
  1596. chat_id, card, metadata, "send_update_prompt failed",
  1597. state_map=self._update_prompt_state, state_id=prompt_id, session_key=session_key,
  1598. )
  1599. except Exception as exc:
  1600. logger.warning("[Feishu] send_update_prompt failed: %s", exc)
  1601. return SendResult(success=False, error=str(exc))
  1602. @staticmethod
  1603. def _build_resolved_approval_card(*, choice: str, user_name: str, body: str | None = None) -> dict[str, Any]:
  1604. """Raw card JSON shown in place of the buttons once an approval is resolved; the request (*body*) stays."""
  1605. icon = "❌" if choice == "deny" else "✅"
  1606. label = t(_APPROVAL_LABEL_KEYS.get(choice, "platform.feishu.approval.resolved_fallback"))
  1607. decided = t("platform.feishu.approval.resolved_by_user", icon=icon, label=label, user=user_name)
  1608. return _card(f"{icon} {label}", "red" if choice == "deny" else "green", f"{body}\n\n{decided}" if body else decided)
  1609. @staticmethod
  1610. def _build_resolved_update_prompt_card(*, answer: str, user_name: str) -> dict[str, Any]:
  1611. yes = answer == "y"
  1612. title = t("platform.feishu.update_prompt.answered_title", icon="✅" if yes else "❌",
  1613. answer=t("platform.feishu.update_prompt.word_yes" if yes else "platform.feishu.update_prompt.word_no"))
  1614. return _card(title, "green" if yes else "red", t("platform.feishu.update_prompt.answered_by", user=user_name))
  1615. @staticmethod
  1616. def _write_update_prompt_response(answer: str) -> None:
  1617. response_path = get_hermes_home() / ".update_response"
  1618. tmp_path = response_path.with_suffix(".tmp")
  1619. tmp_path.write_text(answer, encoding="utf-8")
  1620. tmp_path.replace(response_path)
  1621. async def send_voice(
  1622. self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1623. metadata: Optional[dict[str, Any]] = None, is_voice: Optional[bool] = None, **kwargs,
  1624. ) -> SendResult:
  1625. """Native voice message (Feishu only accepts Opus): non-opus audio is transcoded via ffmpeg
  1626. first; without ffmpeg the original file goes out as a file attachment. ``is_voice=False``
  1627. (an audio MEDIA file without [[audio_as_voice]]: music, a sound effect) is a file
  1628. attachment under its real name, never transcoded into a voice note."""
  1629. if is_voice is False:
  1630. return await self.send_document(
  1631. chat_id, audio_path, caption=caption, reply_to=reply_to, metadata=metadata)
  1632. transcoded_path: Optional[str] = None
  1633. ext = Path(audio_path).suffix.lower()
  1634. if ext not in _FEISHU_OPUS_UPLOAD_EXTENSIONS:
  1635. from gateway.platforms.base import transcode_to_ogg_opus
  1636. transcoded_path = await asyncio.to_thread(transcode_to_ogg_opus, audio_path)
  1637. if transcoded_path:
  1638. audio_path = transcoded_path
  1639. try:
  1640. return await self._send_uploaded_file_message(
  1641. chat_id=chat_id, file_path=audio_path, reply_to=reply_to, metadata=metadata,
  1642. caption=caption, outbound_message_type="audio",
  1643. )
  1644. finally:
  1645. if transcoded_path:
  1646. try:
  1647. os.unlink(transcoded_path)
  1648. except OSError:
  1649. pass
  1650. async def send_document(
  1651. self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
  1652. reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, **kwargs,
  1653. ) -> SendResult:
  1654. """Send a document/file attachment to Feishu."""
  1655. return await self._send_uploaded_file_message(
  1656. chat_id=chat_id, file_path=file_path, reply_to=reply_to, metadata=metadata,
  1657. caption=caption, file_name=file_name,
  1658. )
  1659. async def send_video(
  1660. self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1661. metadata: Optional[dict[str, Any]] = None, **kwargs,
  1662. ) -> SendResult:
  1663. """Send a video file to Feishu."""
  1664. return await self._send_uploaded_file_message(
  1665. chat_id=chat_id, file_path=video_path, reply_to=reply_to, metadata=metadata,
  1666. caption=caption, outbound_message_type="media",
  1667. )
  1668. async def send_image_file(
  1669. self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1670. metadata: Optional[dict[str, Any]] = None, **kwargs,
  1671. ) -> SendResult:
  1672. """Send a local image file to Feishu."""
  1673. if not self._client:
  1674. return SendResult(success=False, error="Not connected")
  1675. if not os.path.exists(image_path):
  1676. return SendResult(success=False, error=f"Image file not found: {image_path}")
  1677. try:
  1678. import io as _io
  1679. image_file = _io.BytesIO(await asyncio.to_thread(Path(image_path).read_bytes)) # lark's MultipartEncoder needs .name and .tell()
  1680. image_file.name = os.path.basename(image_path)
  1681. body = self._build_image_upload_body(image_type=_FEISHU_IMAGE_UPLOAD_TYPE, image=image_file)
  1682. request = self._build_image_upload_request(body)
  1683. upload_response = await self._run_blocking(self._client.im.v1.image.create, request)
  1684. image_key = self._extract_response_field(upload_response, "image_key")
  1685. if not image_key:
  1686. return self._response_error_result(
  1687. upload_response, default_message="image upload failed",
  1688. override_error="Feishu image upload missing image_key",
  1689. )
  1690. message_response = await self._send_uploaded_key(
  1691. chat_id=chat_id, reply_to=reply_to, metadata=metadata, caption=caption,
  1692. key_msg_type="image", key_payload={"image_key": image_key},
  1693. media_tag={"tag": "img", "image_key": image_key},
  1694. )
  1695. return self._finalize_send_result(message_response, "image send failed")
  1696. except Exception as exc:
  1697. logger.error("[Feishu] Failed to send image %s: %s", image_path, exc, exc_info=True)
  1698. return SendResult(success=False, error=str(exc))
  1699. async def send_typing(self, chat_id: str, metadata=None) -> None:
  1700. """Feishu bot API does not expose a typing indicator."""
  1701. return
  1702. async def send_image(
  1703. self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1704. metadata: Optional[dict[str, Any]] = None,
  1705. ) -> SendResult:
  1706. """Download a remote image then send it through the native Feishu image flow."""
  1707. try:
  1708. image_path = await self._download_remote_image(image_url)
  1709. except Exception as exc:
  1710. logger.error("[Feishu] Failed to download image %s: %s", image_url, exc, exc_info=True)
  1711. return await super().send_image(
  1712. chat_id=chat_id, image_url=image_url, caption=caption, reply_to=reply_to, metadata=metadata,
  1713. )
  1714. return await self.send_image_file(
  1715. chat_id=chat_id, image_path=image_path, caption=caption, reply_to=reply_to, metadata=metadata,
  1716. )
  1717. async def send_animation(
  1718. self, chat_id: str, animation_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1719. metadata: Optional[dict[str, Any]] = None,
  1720. ) -> SendResult:
  1721. """Feishu has no native GIF bubble; degrade to a downloadable file."""
  1722. try:
  1723. file_path, file_name = await self._download_remote_document(
  1724. animation_url, default_ext=".gif", preferred_name="animation.gif",
  1725. )
  1726. except Exception as exc:
  1727. logger.error("[Feishu] Failed to download animation %s: %s", animation_url, exc, exc_info=True)
  1728. return await super().send_animation(
  1729. chat_id=chat_id, animation_url=animation_url, caption=caption, reply_to=reply_to, metadata=metadata,
  1730. )
  1731. degraded_caption = self.warning_text(
  1732. t("platform.feishu.media.gif_downgraded_caption", caption=caption) if caption
  1733. else t("platform.feishu.media.gif_downgraded"), caption)
  1734. return await self.send_document(
  1735. chat_id=chat_id, file_path=file_path, file_name=file_name, caption=degraded_caption,
  1736. reply_to=reply_to, metadata=metadata,
  1737. )
  1738. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  1739. """Return real chat metadata from Feishu when available."""
  1740. fallback = {"chat_id": chat_id, "name": chat_id, "type": "dm"}
  1741. if not self._client:
  1742. return fallback
  1743. cached = self._chat_info_cache.get(chat_id)
  1744. if cached is not None:
  1745. return dict(cached)
  1746. try:
  1747. request = self._build_get_chat_request(chat_id)
  1748. response = await self._run_blocking(self._client.im.v1.chat.get, request)
  1749. if not response or getattr(response, "success", lambda: False)() is False:
  1750. code = getattr(response, "code", "unknown")
  1751. msg = getattr(response, "msg", "chat lookup failed")
  1752. logger.warning("[Feishu] Failed to get chat info for %s: [%s] %s", chat_id, code, msg)
  1753. return fallback
  1754. data = getattr(response, "data", None)
  1755. raw_chat_type = str(getattr(data, "chat_type", "") or "").strip().lower()
  1756. info = {
  1757. "chat_id": chat_id, "name": str(getattr(data, "name", None) or chat_id),
  1758. "type": self._map_chat_type(raw_chat_type), "raw_type": raw_chat_type or None,
  1759. }
  1760. self._chat_info_cache[chat_id] = info
  1761. return dict(info)
  1762. except Exception:
  1763. logger.warning("[Feishu] Failed to get chat info for %s", chat_id, exc_info=True)
  1764. return fallback
  1765. def format_message(self, content: str) -> str:
  1766. """Feishu text messages are plain text by default."""
  1767. return content.strip()
  1768. # --- Inbound event handlers ---
  1769. def _on_message_event(self, data: Any) -> None:
  1770. """SDK dispatcher callback (background thread); queues for replay while the loop isn't ready."""
  1771. loop = self._loop
  1772. if not self._loop_accepts_callbacks(loop):
  1773. if self._enqueue_pending_inbound_event(data):
  1774. # Replayed events hop onto the loop from THIS thread's context; keep the WS thread's
  1775. # profile scope (see _connect_websocket) rather than starting from an empty one.
  1776. threading.Thread(
  1777. target=contextvars.copy_context().run, args=(self._drain_pending_inbound_events,),
  1778. name="feishu-pending-inbound-drainer", daemon=True,
  1779. ).start()
  1780. return
  1781. self._submit_on_loop(loop, self._handle_message_event_data(data))
  1782. def _enqueue_pending_inbound_event(self, data: Any) -> bool:
  1783. """Queue an event for replay; True when the caller should spawn the (single) drainer thread."""
  1784. with self._pending_inbound_lock:
  1785. if len(self._pending_inbound_events) >= self._pending_inbound_max_depth:
  1786. # Full — drop the oldest (loop unavailable for long AND WS still firing).
  1787. dropped = self._pending_inbound_events.pop(0)
  1788. try:
  1789. message = getattr(getattr(dropped, "event", None), "message", None)
  1790. message_id = str(getattr(message, "message_id", "") or "unknown")
  1791. except Exception:
  1792. message_id = "unknown"
  1793. logger.error(
  1794. "[Feishu] Pending-inbound queue full (%d); dropped oldest event %s",
  1795. self._pending_inbound_max_depth, message_id,
  1796. )
  1797. self._pending_inbound_events.append(data)
  1798. depth = len(self._pending_inbound_events)
  1799. should_start = not self._pending_drain_scheduled
  1800. self._pending_drain_scheduled = True
  1801. logger.warning("[Feishu] Queued inbound event for replay (loop not ready, queue depth=%d)", depth)
  1802. return should_start
  1803. def _drain_pending_inbound_events(self) -> None:
  1804. """Daemon-thread drainer: replay queued inbound events once the loop is ready (or drop on shutdown/timeout)."""
  1805. poll_interval = 0.25
  1806. max_wait_seconds = 120.0 # safety cap: drop queue after 2 minutes
  1807. waited = 0.0
  1808. def _take_all() -> list[Any]:
  1809. with self._pending_inbound_lock:
  1810. batch = self._pending_inbound_events[:]
  1811. self._pending_inbound_events.clear()
  1812. return batch
  1813. def _queue_empty() -> bool:
  1814. with self._pending_inbound_lock:
  1815. return not self._pending_inbound_events
  1816. try:
  1817. while True:
  1818. if not getattr(self, "_running", True):
  1819. # Shutting down — drop rather than hold events against a closed loop.
  1820. dropped = len(_take_all())
  1821. if dropped:
  1822. logger.warning("[Feishu] Dropped %d queued inbound event(s) during shutdown", dropped)
  1823. return
  1824. loop = self._loop
  1825. if self._loop_accepts_callbacks(loop):
  1826. batch = _take_all()
  1827. if not batch:
  1828. if _queue_empty(): # emptied between check and grab
  1829. return
  1830. continue
  1831. # Loop closed/unavailable mid-batch → requeue those and poll again.
  1832. requeue = [e for e in batch if not self._submit_on_loop(loop, self._handle_message_event_data(e))]
  1833. if requeue:
  1834. with self._pending_inbound_lock:
  1835. self._pending_inbound_events[:0] = requeue
  1836. if len(batch) - len(requeue):
  1837. logger.info("[Feishu] Replayed %d queued inbound event(s)", len(batch) - len(requeue))
  1838. if not requeue and _queue_empty(): # fully drained and nothing new arrived
  1839. return
  1840. continue
  1841. if waited >= max_wait_seconds:
  1842. logger.error(
  1843. "[Feishu] Adapter loop unavailable for %.0fs; dropped %d queued inbound event(s)",
  1844. max_wait_seconds, len(_take_all()),
  1845. )
  1846. return
  1847. time.sleep(poll_interval)
  1848. waited += poll_interval
  1849. finally:
  1850. with self._pending_inbound_lock:
  1851. self._pending_drain_scheduled = False
  1852. async def _handle_message_event_data(self, data: Any) -> None:
  1853. """Shared inbound message handling for websocket and webhook transports."""
  1854. event = getattr(data, "event", None)
  1855. message = getattr(event, "message", None)
  1856. sender = getattr(event, "sender", None)
  1857. if not message or not sender or not getattr(sender, "sender_id", None):
  1858. logger.debug("[Feishu] Dropping malformed inbound event: missing message/sender")
  1859. return
  1860. message_id = getattr(message, "message_id", None)
  1861. if not message_id or await self._is_duplicate(message_id):
  1862. logger.debug("[Feishu] Dropping duplicate/missing message_id: %s", message_id)
  1863. return
  1864. reason = self._admit(sender, message)
  1865. if reason is not None:
  1866. logger.debug("[Feishu] dropping inbound event: %s", reason)
  1867. if reason == "group_policy_rejected":
  1868. self._warn_once_empty_allowlist_deny(getattr(message, "chat_id", "") or "")
  1869. return
  1870. await self._process_inbound_message(
  1871. data=data, message=message, sender_id=getattr(sender, "sender_id", None),
  1872. chat_type=getattr(message, "chat_type", "p2p"), message_id=message_id, is_bot=_is_bot_sender(sender),
  1873. )
  1874. def _on_message_read_event(self, data: P2ImMessageMessageReadV1) -> None:
  1875. """Ignore read-receipt events that Hermes does not act on."""
  1876. message = getattr(getattr(data, "event", None), "message", None)
  1877. logger.debug("[Feishu] Ignoring message_read event: %s", getattr(message, "message_id", None) or "")
  1878. def _on_bot_membership_change(self, data: Any, verb: str) -> None:
  1879. chat_id = str(getattr(getattr(data, "event", None), "chat_id", "") or "")
  1880. logger.info("[Feishu] Bot %s chat: %s", verb, chat_id)
  1881. self._chat_info_cache.pop(chat_id, None)
  1882. def _on_bot_added_to_chat(self, data: Any) -> None:
  1883. self._on_bot_membership_change(data, "added to")
  1884. def _on_bot_removed_from_chat(self, data: Any) -> None:
  1885. self._on_bot_membership_change(data, "removed from")
  1886. def _on_p2p_chat_entered(self, data: Any) -> None:
  1887. logger.debug("[Feishu] User entered P2P chat with bot")
  1888. def _on_message_recalled(self, data: Any) -> None:
  1889. logger.debug("[Feishu] Message recalled by user")
  1890. def _submit_if_ready(self, label: str, make_coro: Any) -> None:
  1891. """Schedule ``make_coro()`` on the adapter loop, or log-and-drop when the loop isn't ready."""
  1892. loop = self._loop
  1893. if not self._loop_accepts_callbacks(loop):
  1894. logger.warning("[Feishu] Dropping %s before adapter loop is ready", label)
  1895. return
  1896. self._submit_on_loop(loop, make_coro())
  1897. def _on_drive_comment_event(self, data: Any) -> None:
  1898. """drive.notice.comment_add_v1 → feishu_comment.handle_drive_comment_event on the adapter loop."""
  1899. from plugins.platforms.feishu.feishu_comment import handle_drive_comment_event
  1900. self._submit_if_ready("drive comment event", lambda: handle_drive_comment_event(
  1901. self._client, data, self_open_id=self._bot_open_id, secondary=bool(getattr(self, "_owner_profile", None))))
  1902. def _on_meeting_invited_event(self, data: Any) -> None:
  1903. """vc.bot.meeting_invited_v1 → feishu_meeting_invite.handle_meeting_invited_event."""
  1904. from plugins.platforms.feishu.feishu_meeting_invite import handle_meeting_invited_event
  1905. self._submit_if_ready("meeting invite event", lambda: handle_meeting_invited_event(self, data))
  1906. def _on_reaction_event(self, event_type: str, data: Any) -> None:
  1907. """Route user reactions on bot messages as synthetic text events."""
  1908. event = getattr(data, "event", None)
  1909. message_id = str(getattr(event, "message_id", "") or "")
  1910. operator_type = str(getattr(event, "operator_type", "") or "")
  1911. reaction_type_obj = getattr(event, "reaction_type", None)
  1912. emoji_type = str(getattr(reaction_type_obj, "emoji_type", "") or "")
  1913. action = "added" if "created" in event_type else "removed"
  1914. logger.debug(
  1915. "[Feishu] Reaction %s on message %s (operator_type=%s, emoji=%s)",
  1916. action, message_id, operator_type, emoji_type,
  1917. )
  1918. # Drop bot/app-origin reactions to break the feedback loop from our own lifecycle
  1919. # reactions; a human clicking the same emoji is still routed through.
  1920. loop = self._loop
  1921. if operator_type in {"bot", "app"} or not message_id or not self._loop_accepts_callbacks(loop):
  1922. return
  1923. self._submit_on_loop(loop, self._handle_reaction_event(event_type, data))
  1924. def _on_card_action_trigger(self, data: Any) -> Any:
  1925. """Synchronous SDK card-action callback.
  1926. Approval/update-prompt/clarify/picker buttons return the settled card inline (the only
  1927. reliable way to sync all clients) and schedule any async resolution; other clicks are routed
  1928. as synthetic commands via ``_handle_card_action_event``.
  1929. """
  1930. loop = self._loop
  1931. if not self._loop_accepts_callbacks(loop):
  1932. logger.warning("[Feishu] Dropping card action before adapter loop is ready")
  1933. return self._card_response()
  1934. event = getattr(data, "event", None)
  1935. action = getattr(event, "action", None)
  1936. action_value = getattr(action, "value", {}) or {}
  1937. for key, handler in self._CARD_ACTION_ROUTES if isinstance(action_value, dict) else ():
  1938. if action_value.get(key):
  1939. return getattr(self, handler)(event=event, action_value=action_value, loop=loop)
  1940. self._submit_on_loop(loop, self._handle_card_action_event(data))
  1941. return self._card_response()
  1942. @staticmethod
  1943. def _loop_accepts_callbacks(loop: Any) -> bool:
  1944. """Return True when the adapter loop can accept thread-safe submissions."""
  1945. return loop is not None and not bool(getattr(loop, "is_closed", lambda: False)())
  1946. def _submit_on_loop(self, loop: Any, coro: Any) -> bool:
  1947. """Schedule background work on the adapter loop with shared failure logging."""
  1948. from agent.async_utils import safe_schedule_threadsafe
  1949. future = safe_schedule_threadsafe(
  1950. coro, loop, logger=logger, log_message="[Feishu] Failed to schedule background callback work",
  1951. log_level=logging.WARNING,
  1952. )
  1953. if future is None:
  1954. return False
  1955. future.add_done_callback(self._log_background_failure)
  1956. return True
  1957. def _is_interactive_operator_authorized(
  1958. self, open_id: str, *, user_id: str = "", union_id: str = "", chat_id: str = "",
  1959. ) -> bool:
  1960. """Return whether this card-action operator may answer gated prompts.
  1961. Feishu admins / FEISHU_ALLOWED_USERS decide when set. With neither (setup's pairing-mode
  1962. default) the clicker must pass the gateway authorization inbound messages get (pairing
  1963. store, GATEWAY_ALLOWED_USERS, ...), so a chat member who may not use the bot can't answer.
  1964. """
  1965. normalized = str(open_id or "").strip()
  1966. if not normalized:
  1967. return False
  1968. allowed_ids = set(self._admins) | set(self._allowed_group_users)
  1969. if allowed_ids:
  1970. # Lists may name a user by any id intake accepts (_sender_identity).
  1971. operator_ids = {normalized, str(user_id or "").strip(), str(union_id or "").strip()} - {""}
  1972. return "*" in allowed_ids or bool(operator_ids & allowed_ids)
  1973. # SessionSource.user_id is the tenant user_id, else open_id (_resolve_sender_profile).
  1974. principal = str(user_id or "").strip() or normalized
  1975. # Feishu chat ids don't say DM vs group; "group" is the check's own default.
  1976. verdict = self._is_sender_authorized(principal, "group", str(chat_id or "") or None)
  1977. if verdict is None:
  1978. logger.debug("[Feishu] No gateway authorization check for card operator %s; denying", normalized)
  1979. return False
  1980. return verdict
  1981. @staticmethod
  1982. def _card_response(card_data: Optional[dict[str, Any]] = None) -> Any:
  1983. """Synchronous card-callback response; ``card_data`` updates the card inline."""
  1984. if P2CardActionTriggerResponse is None:
  1985. return None
  1986. response = P2CardActionTriggerResponse()
  1987. if card_data is not None and CallBackCard is not None:
  1988. card = CallBackCard()
  1989. card.type = "raw"
  1990. card.data = card_data
  1991. response.card = card
  1992. return response
  1993. def _validate_card_action(
  1994. self, *, event: Any, state: dict[str, str], label: str, ident: Any,
  1995. ) -> Optional[tuple[str, str, str, str, str]]:
  1996. """Shared operator/chat checks for approval + update-prompt clicks.
  1997. Returns ``(open_id, callback_chat_id, user_name, user_id, union_id)`` or None (already logged).
  1998. """
  1999. operator = getattr(event, "operator", None)
  2000. open_id = str(getattr(operator, "open_id", "") or "")
  2001. user_id = str(getattr(operator, "user_id", "") or "")
  2002. union_id = str(getattr(operator, "union_id", "") or "")
  2003. callback_chat_id = str(getattr(getattr(event, "context", None), "open_chat_id", "") or "")
  2004. expected_chat_id = str(state.get("chat_id", "") or "")
  2005. if not self._is_interactive_operator_authorized(
  2006. open_id, user_id=user_id, union_id=union_id, chat_id=expected_chat_id or callback_chat_id,
  2007. ):
  2008. logger.warning("[Feishu] Unauthorized %s click by %s", label, open_id or "<unknown>")
  2009. return None
  2010. if callback_chat_id and expected_chat_id and callback_chat_id != expected_chat_id:
  2011. logger.warning(
  2012. "[Feishu] %s callback chat mismatch for %s (expected=%s, got=%s)",
  2013. label.capitalize(), ident, expected_chat_id, callback_chat_id,
  2014. )
  2015. return None
  2016. return open_id, callback_chat_id, self._get_cached_sender_name(open_id) or open_id, user_id, union_id
  2017. def _handle_approval_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:
  2018. """Schedule approval resolution and build the synchronous callback response."""
  2019. approval_id = action_value.get("approval_id")
  2020. if approval_id is None:
  2021. logger.debug("[Feishu] Card action missing approval_id, ignoring")
  2022. return self._card_response()
  2023. state = self._approval_state.get(approval_id)
  2024. if not state:
  2025. logger.debug("[Feishu] Approval %s already resolved or unknown", approval_id)
  2026. return self._card_response()
  2027. choice = _APPROVAL_CHOICE_MAP.get(action_value.get("hermes_action"), "deny")
  2028. checked = self._validate_card_action(event=event, state=state, label="approval", ident=approval_id)
  2029. if checked is None:
  2030. return self._card_response()
  2031. open_id, chat_id, user_name, user_id, union_id = checked
  2032. coro = self._resolve_approval(
  2033. approval_id=approval_id, choice=choice, user_name=user_name, open_id=open_id, chat_id=chat_id,
  2034. user_id=user_id, union_id=union_id,
  2035. )
  2036. if not self._submit_on_loop(loop, coro):
  2037. return self._card_response()
  2038. return self._card_response(self._build_resolved_approval_card(choice=choice, user_name=user_name, body=state.get("body")))
  2039. def _handle_update_prompt_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:
  2040. """Schedule update prompt resolution and build the synchronous callback response."""
  2041. prompt_id = action_value.get("update_prompt_id")
  2042. if prompt_id is None:
  2043. logger.debug("[Feishu] Card action missing update_prompt_id, ignoring")
  2044. return self._card_response()
  2045. state = self._update_prompt_state.get(prompt_id)
  2046. if not state:
  2047. logger.debug("[Feishu] Update prompt %s already resolved or unknown", prompt_id)
  2048. return self._card_response()
  2049. answer = str(action_value.get("hermes_update_prompt_action", "") or "").strip().lower()
  2050. if answer not in {"y", "n"}:
  2051. logger.debug("[Feishu] Card action has invalid update prompt answer=%r", answer)
  2052. return self._card_response()
  2053. checked = self._validate_card_action(event=event, state=state, label="update prompt", ident=prompt_id)
  2054. if checked is None:
  2055. return self._card_response()
  2056. open_id, chat_id, user_name, user_id, union_id = checked
  2057. coro = self._resolve_update_prompt(
  2058. prompt_id, answer, user_name, open_id=open_id, chat_id=chat_id, user_id=user_id, union_id=union_id,
  2059. )
  2060. if not self._submit_on_loop(loop, coro):
  2061. return self._card_response()
  2062. return self._card_response(self._build_resolved_update_prompt_card(answer=answer, user_name=user_name))
  2063. def _pop_validated_prompt_state(
  2064. self, *, states: dict[int, dict[str, str]], ident: Any, label: str, open_id: str, chat_id: str,
  2065. unauthorized_fmt: str, operator_repr: str, user_id: str = "", union_id: str = "",
  2066. ) -> Optional[dict[str, str]]:
  2067. """Re-validate on the loop thread (state may have changed since the callback) and pop."""
  2068. state = states.get(ident)
  2069. if not state:
  2070. logger.debug("[Feishu] %s %s already resolved or unknown", label, ident)
  2071. return None
  2072. if not self._is_interactive_operator_authorized(
  2073. open_id, user_id=user_id, union_id=union_id, chat_id=str(state.get("chat_id", "") or "") or chat_id,
  2074. ):
  2075. logger.warning(unauthorized_fmt, operator_repr, ident)
  2076. return None
  2077. expected_chat_id = str(state.get("chat_id", "") or "")
  2078. if expected_chat_id and chat_id and expected_chat_id != chat_id:
  2079. logger.warning("[Feishu] %s %s chat mismatch (expected=%s, got=%s)", label, ident, expected_chat_id, chat_id)
  2080. return None
  2081. state = states.pop(ident, None)
  2082. if not state:
  2083. logger.debug("[Feishu] %s %s already resolved while validating callback", label, ident)
  2084. return state
  2085. async def _resolve_approval(
  2086. self, approval_id: Any, choice: str, user_name: str, *, open_id: str = "", chat_id: str = "",
  2087. user_id: str = "", union_id: str = "",
  2088. ) -> None:
  2089. """Pop approval state and unblock the waiting agent thread."""
  2090. state = self._pop_validated_prompt_state(
  2091. states=self._approval_state, ident=approval_id, label="Approval", open_id=open_id, chat_id=chat_id,
  2092. unauthorized_fmt="[Feishu] Unauthorized approval click by %s for approval %s",
  2093. operator_repr=open_id or "<unknown>", user_id=user_id, union_id=union_id,
  2094. )
  2095. if not state:
  2096. return
  2097. try:
  2098. from tools.approval import resolve_gateway_approval_card
  2099. count = resolve_gateway_approval_card(state["session_key"], choice, state.get("request_id"))
  2100. logger.info(
  2101. "Feishu button resolved %d approval(s) for session %s (choice=%s, user=%s)",
  2102. count, state["session_key"], choice, user_name,
  2103. )
  2104. if not count and choice != "deny":
  2105. # The card already reads "Approved" (synchronous callback), but nothing was
  2106. # waiting — the wait timed out (fail-closed deny) or was resolved via /approve.
  2107. # Correct the record so the user doesn't believe the command ran.
  2108. _chat = str(state.get("chat_id", "") or chat_id or "")
  2109. if _chat:
  2110. try:
  2111. await self.send(
  2112. _chat,
  2113. t("platform.shared.approval_expired"),
  2114. )
  2115. except Exception:
  2116. logger.debug("[Feishu] expired-approval notice failed", exc_info=True)
  2117. except Exception as exc:
  2118. logger.error("Failed to resolve gateway approval from Feishu button: %s", exc)
  2119. async def _resolve_update_prompt(
  2120. self, prompt_id: Any, answer: str, user_name: str, *, open_id: str = "", chat_id: str = "",
  2121. user_id: str = "", union_id: str = "",
  2122. ) -> None:
  2123. """Persist an update prompt answer for the detached update process."""
  2124. state = self._pop_validated_prompt_state(
  2125. states=self._update_prompt_state, ident=prompt_id, label="Update prompt", open_id=open_id,
  2126. chat_id=chat_id, unauthorized_fmt="[Feishu] Unauthorized update prompt click by %s for prompt %s",
  2127. operator_repr=open_id, user_id=user_id, union_id=union_id,
  2128. )
  2129. if not state:
  2130. return
  2131. try:
  2132. self._write_update_prompt_response(answer)
  2133. logger.info(
  2134. "Feishu update prompt resolved for session %s (answer=%s, user=%s)",
  2135. state["session_key"], answer, user_name,
  2136. )
  2137. except Exception as exc:
  2138. logger.error("Failed to resolve Feishu update prompt: %s", exc)
  2139. async def _handle_reaction_event(self, event_type: str, data: Any) -> None:
  2140. """Fetch the reacted-to message; if it was sent by this bot, emit a synthetic text event."""
  2141. if not self._client:
  2142. return
  2143. event = getattr(data, "event", None)
  2144. message_id = str(getattr(event, "message_id", "") or "")
  2145. if not message_id:
  2146. return
  2147. # Fetch the target message to verify it was sent by us and to obtain chat context.
  2148. try:
  2149. request = self._build_get_message_request(message_id)
  2150. response = await self._run_blocking(self._client.im.v1.message.get, request)
  2151. if not self._response_succeeded(response):
  2152. return
  2153. items = getattr(getattr(response, "data", None), "items", None) or []
  2154. msg = items[0] if items else None
  2155. if not msg:
  2156. return
  2157. # GET im/v1/messages reports sender.id=app_id for bot messages — peer bots share
  2158. # sender_type="app" with us but differ on app_id. Only route our own messages.
  2159. sender = getattr(msg, "sender", None)
  2160. if str(getattr(sender, "id", "") or "") != self._app_id:
  2161. return
  2162. chat_id = str(getattr(msg, "chat_id", "") or "")
  2163. chat_type_raw = str(getattr(msg, "chat_type", "p2p") or "p2p")
  2164. if not chat_id:
  2165. return
  2166. except Exception:
  2167. logger.debug("[Feishu] Failed to fetch message for reaction routing", exc_info=True)
  2168. return
  2169. user_id_obj = getattr(event, "user_id", None)
  2170. reaction_type_obj = getattr(event, "reaction_type", None)
  2171. emoji_type = str(getattr(reaction_type_obj, "emoji_type", "") or "UNKNOWN")
  2172. action = "added" if "created" in event_type else "removed"
  2173. synthetic_text = f"reaction:{action}:{emoji_type}"
  2174. logger.info("[Feishu] Routing reaction %s:%s on bot message %s as synthetic event", action, emoji_type, message_id)
  2175. await self._dispatch_synthetic_event(
  2176. text=synthetic_text, message_type=MessageType.TEXT, chat_id=chat_id, sender_id=user_id_obj,
  2177. event_chat_type=chat_type_raw, raw_message=data, message_id=message_id,
  2178. )
  2179. def _is_card_action_duplicate(self, token: str) -> bool:
  2180. """Return True if this card action token was already processed within the dedup window."""
  2181. now = time.time()
  2182. # Prune expired tokens lazily each call.
  2183. expired = [t for t, ts in self._card_action_tokens.items() if now - ts > _FEISHU_CARD_ACTION_DEDUP_TTL_SECONDS]
  2184. for t in expired:
  2185. del self._card_action_tokens[t]
  2186. if token in self._card_action_tokens:
  2187. return True
  2188. self._card_action_tokens[token] = now
  2189. return False
  2190. async def _handle_card_action_event(self, data: Any) -> None:
  2191. """Route Feishu interactive card button clicks as synthetic COMMAND events."""
  2192. event = getattr(data, "event", None)
  2193. token = str(getattr(event, "token", "") or "")
  2194. if token and self._is_card_action_duplicate(token):
  2195. logger.debug("[Feishu] Dropping duplicate card action token: %s", token)
  2196. return
  2197. context = getattr(event, "context", None)
  2198. chat_id = str(getattr(context, "open_chat_id", "") or "")
  2199. operator = getattr(event, "operator", None)
  2200. open_id = str(getattr(operator, "open_id", "") or "")
  2201. if not chat_id or not open_id:
  2202. logger.debug("[Feishu] Card action missing chat_id or operator open_id, dropping")
  2203. return
  2204. action = getattr(event, "action", None)
  2205. action_tag = str(getattr(action, "tag", "") or "button")
  2206. action_value = getattr(action, "value", {}) or {}
  2207. synthetic_text = f"/card {action_tag}"
  2208. if action_value:
  2209. try:
  2210. synthetic_text += f" {json.dumps(action_value, ensure_ascii=False)}"
  2211. except Exception:
  2212. pass
  2213. logger.info("[Feishu] Routing card action %r from %s in %s as synthetic command", action_tag, open_id, chat_id)
  2214. await self._dispatch_synthetic_event(
  2215. text=synthetic_text, message_type=MessageType.COMMAND, chat_id=chat_id,
  2216. sender_id=SimpleNamespace(open_id=open_id, user_id=None, union_id=None), event_chat_type="group",
  2217. raw_message=data, message_id=token or str(uuid.uuid4()),
  2218. )
  2219. async def _dispatch_synthetic_event(
  2220. self, *, text: str, message_type: MessageType, chat_id: str, sender_id: Any, event_chat_type: str,
  2221. raw_message: Any, message_id: str,
  2222. ) -> None:
  2223. """Wrap a reaction/card click as a MessageEvent and run it through the guarded pipeline."""
  2224. sender_profile = await self._resolve_sender_profile(sender_id)
  2225. chat_info = await self.get_chat_info(chat_id)
  2226. source = self.build_source(
  2227. chat_id=chat_id,
  2228. chat_name=chat_info.get("name") or chat_id or "Feishu Chat",
  2229. chat_type=self._resolve_source_chat_type(chat_info=chat_info, event_chat_type=event_chat_type),
  2230. user_id=sender_profile["user_id"],
  2231. user_name=sender_profile["user_name"],
  2232. thread_id=None,
  2233. user_id_alt=sender_profile["user_id_alt"],
  2234. )
  2235. synthetic_event = MessageEvent(
  2236. text=text, message_type=message_type, source=source, raw_message=raw_message,
  2237. message_id=message_id, channel_prompt=self._resolve_channel_prompt(chat_id),
  2238. timestamp=datetime.now(),
  2239. )
  2240. await self._handle_message_with_guards(synthetic_event)
  2241. # --- Per-chat serialization and typing indicator ---
  2242. def _get_chat_lock(self, chat_id: str) -> asyncio.Lock:
  2243. """Per-chat asyncio.Lock for serial processing; LRU-bounded, never evicts a held lock if any is free."""
  2244. lock = self._chat_locks.get(chat_id)
  2245. if lock is not None:
  2246. self._chat_locks.move_to_end(chat_id)
  2247. return lock
  2248. if len(self._chat_locks) >= self.CHAT_LOCK_MAX_SIZE:
  2249. victim = next((k for k, lk in self._chat_locks.items() if not lk.locked()), next(iter(self._chat_locks)))
  2250. self._chat_locks.pop(victim)
  2251. lock = asyncio.Lock()
  2252. self._chat_locks[chat_id] = lock
  2253. return lock
  2254. async def _handle_message_with_guards(self, event: MessageEvent) -> None:
  2255. """Run one event through the agent pipeline under the per-chat lock (openclaw createChatQueue)."""
  2256. chat_id = getattr(event.source, "chat_id", "") or "" if event.source else ""
  2257. chat_lock = self._get_chat_lock(chat_id)
  2258. async with chat_lock:
  2259. await self.handle_message(event)
  2260. # --- Processing status reactions ---
  2261. def _reactions_enabled(self) -> bool:
  2262. return str(_get_scoped_secret("FEISHU_REACTIONS", "true")).strip().lower() not in {"false", "0", "no"}
  2263. async def _reaction_call(self, verb: str, message_id: str, ident: str, build_request: Any, api: Any) -> Any:
  2264. """Shared add/remove reaction wrapper: returns the response data on success, else None (logged)."""
  2265. try:
  2266. response = await self._run_blocking(api, build_request())
  2267. if self._response_succeeded(response):
  2268. return getattr(response, "data", None) or True
  2269. logger.debug(
  2270. "[Feishu] %s reaction %s on %s rejected: code=%s msg=%s",
  2271. verb, ident, message_id, getattr(response, "code", None), getattr(response, "msg", None),
  2272. )
  2273. except Exception:
  2274. logger.warning("[Feishu] %s reaction %s on %s raised", verb, ident, message_id, exc_info=True)
  2275. return None
  2276. async def _add_reaction(self, message_id: str, emoji_type: str) -> Optional[str]:
  2277. """Return the reaction_id on success, else None. The id is needed later for deletion."""
  2278. if not self._client or not message_id or not emoji_type:
  2279. return None
  2280. def _build() -> Any: # lazy SDK import stays inside the guarded call
  2281. from lark_oapi.api.im.v1 import CreateMessageReactionRequest, CreateMessageReactionRequestBody
  2282. body = CreateMessageReactionRequestBody.builder().reaction_type({"emoji_type": emoji_type}).build()
  2283. return CreateMessageReactionRequest.builder().message_id(message_id).request_body(body).build()
  2284. data = await self._reaction_call("Add", message_id, emoji_type, _build, self._client.im.v1.message_reaction.create)
  2285. return getattr(data, "reaction_id", None) if data is not None else None
  2286. async def _remove_reaction(self, message_id: str, reaction_id: str) -> bool:
  2287. if not self._client or not message_id or not reaction_id:
  2288. return False
  2289. def _build() -> Any:
  2290. from lark_oapi.api.im.v1 import DeleteMessageReactionRequest
  2291. return DeleteMessageReactionRequest.builder().message_id(message_id).reaction_id(reaction_id).build()
  2292. data = await self._reaction_call("Remove", message_id, reaction_id, _build, self._client.im.v1.message_reaction.delete)
  2293. return data is not None
  2294. async def on_processing_start(self, event: MessageEvent) -> None:
  2295. message_id = event.message_id
  2296. if not self._reactions_enabled() or not message_id or message_id in self._pending_processing_reactions:
  2297. return
  2298. reaction_id = await self._add_reaction(message_id, _FEISHU_REACTION_IN_PROGRESS)
  2299. if reaction_id:
  2300. cache = self._pending_processing_reactions
  2301. cache[message_id] = reaction_id
  2302. cache.move_to_end(message_id)
  2303. while len(cache) > _FEISHU_PROCESSING_REACTION_CACHE_SIZE:
  2304. cache.popitem(last=False)
  2305. async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None:
  2306. message_id = event.message_id
  2307. if not self._reactions_enabled() or not message_id:
  2308. return
  2309. start_reaction_id = self._pending_processing_reactions.get(message_id)
  2310. if start_reaction_id:
  2311. if not await self._remove_reaction(message_id, start_reaction_id):
  2312. # Don't stack a second badge on a Typing we couldn't remove (UI would read as both
  2313. # "working" and "done/failed"); keep the handle so LRU eventually evicts it.
  2314. return
  2315. self._pending_processing_reactions.pop(message_id, None)
  2316. if outcome is ProcessingOutcome.FAILURE:
  2317. await self._add_reaction(message_id, _FEISHU_REACTION_FAILURE)
  2318. # --- Webhook server and security ---
  2319. def _record_webhook_anomaly(self, remote_ip: str, status: str) -> None:
  2320. """Count consecutive error responses per IP (openclaw createWebhookAnomalyTracker); WARN every threshold."""
  2321. now = time.time()
  2322. count, _last_status, first_seen = self._webhook_anomaly_counts.get(remote_ip) or (0, "", now)
  2323. if count and now - first_seen >= _FEISHU_WEBHOOK_ANOMALY_TTL_SECONDS:
  2324. count, first_seen = 0, now # TTL expired — start fresh
  2325. count += 1
  2326. if count % _FEISHU_WEBHOOK_ANOMALY_THRESHOLD == 0:
  2327. logger.warning(
  2328. "[Feishu] Webhook anomaly: %d consecutive error responses (%s) from %s over the last %.0fs",
  2329. count, status, remote_ip, now - first_seen,
  2330. )
  2331. self._webhook_anomaly_counts[remote_ip] = (count, status, first_seen)
  2332. def _clear_webhook_anomaly(self, remote_ip: str) -> None:
  2333. """Reset the anomaly counter for remote_ip after a successful request."""
  2334. self._webhook_anomaly_counts.pop(remote_ip, None)
  2335. # --- Inbound processing pipeline ---
  2336. def _resolve_channel_prompt(self, chat_id: str, parent_id: str | None = None) -> str | None:
  2337. """Honour ``channel_prompts: {<chat_id>: "<prompt>"}`` in PlatformConfig.extra (as Discord/Slack do)."""
  2338. from gateway.platforms.base import resolve_channel_prompt
  2339. extra = getattr(getattr(self, "config", None), "extra", None) or {} # tests build bare adapters
  2340. return resolve_channel_prompt(extra, chat_id, parent_id)
  2341. async def _process_inbound_message(
  2342. self, *, data: Any, message: Any, sender_id: Any, chat_type: str, message_id: str, is_bot: bool = False,
  2343. ) -> None:
  2344. text, inbound_type, media_urls, media_types, media_text_inlined, mentions = await self._extract_message_content(message)
  2345. if inbound_type == MessageType.TEXT:
  2346. text = _strip_edge_self_mentions(text, mentions)
  2347. if text.startswith("/"):
  2348. inbound_type = MessageType.COMMAND
  2349. # Post-strip guard so a pure "@Bot" message (stripped to "") is dropped.
  2350. if inbound_type == MessageType.TEXT and not text and not media_urls:
  2351. logger.debug("[Feishu] Ignoring empty text message id=%s", message_id)
  2352. return
  2353. if inbound_type != MessageType.COMMAND:
  2354. hint = _build_mention_hint(mentions)
  2355. if hint:
  2356. text = f"{hint}\n\n{text}" if text else hint
  2357. # Only a native ``thread_id`` marks a topic. ``root_id`` is present on every quoted reply
  2358. # too, so using it as a fallback (#19711) turned ordinary quote replies into topic
  2359. # sessions and pushed the bot's answer into a fresh thread (#20548).
  2360. thread_id = getattr(message, "thread_id", None) or None
  2361. reply_to_message_id = (
  2362. getattr(message, "parent_id", None) or getattr(message, "upper_message_id", None)
  2363. or getattr(message, "root_id", None) or None
  2364. )
  2365. reply_to_text = await self._fetch_message_text(reply_to_message_id) if reply_to_message_id else None
  2366. sender_primary = (
  2367. getattr(sender_id, "open_id", None) or getattr(sender_id, "user_id", None)
  2368. or getattr(sender_id, "union_id", None) or "<unknown>"
  2369. )
  2370. chat_id = getattr(message, "chat_id", "") or ""
  2371. logger.info(
  2372. "[Feishu] Inbound %s message received: id=%s type=%s chat_id=%s sender=%s:%s text=%r media=%d",
  2373. "dm" if chat_type == "p2p" else "group", message_id, inbound_type.value, chat_id,
  2374. "bot" if is_bot else "user", sender_primary, text[:120], len(media_urls),
  2375. )
  2376. chat_info = await self.get_chat_info(chat_id)
  2377. sender_profile = await self._resolve_sender_profile(sender_id, is_bot=is_bot)
  2378. source = self.build_source(
  2379. chat_id=chat_id,
  2380. chat_name=chat_info.get("name") or chat_id or "Feishu Chat",
  2381. chat_type=self._resolve_source_chat_type(chat_info=chat_info, event_chat_type=chat_type),
  2382. user_id=sender_profile["user_id"],
  2383. user_name=sender_profile["user_name"],
  2384. thread_id=thread_id,
  2385. user_id_alt=sender_profile["user_id_alt"],
  2386. is_bot=is_bot,
  2387. message_id=message_id,
  2388. )
  2389. normalized = MessageEvent(
  2390. text=text, message_type=inbound_type, source=source, raw_message=data,
  2391. message_id=message_id, media_urls=media_urls, media_types=media_types,
  2392. media_text_inlined=media_text_inlined,
  2393. reply_to_message_id=reply_to_message_id, reply_to_text=reply_to_text,
  2394. channel_prompt=self._resolve_channel_prompt(chat_id, thread_id or None),
  2395. timestamp=datetime.now(),
  2396. )
  2397. await self._dispatch_inbound_event(normalized)
  2398. async def _dispatch_inbound_event(self, event: MessageEvent) -> None:
  2399. """Apply Feishu-specific burst protection before entering the base adapter."""
  2400. if event.message_type == MessageType.TEXT and not event.is_command():
  2401. await self._enqueue_text_event(event)
  2402. return
  2403. if self._should_batch_media_event(event):
  2404. await self._enqueue_media_event(event)
  2405. return
  2406. await self._handle_message_with_guards(event)
  2407. # --- Media batching ---
  2408. def _should_batch_media_event(self, event: MessageEvent) -> bool:
  2409. batchable = {MessageType.PHOTO, MessageType.VIDEO, MessageType.DOCUMENT, MessageType.AUDIO}
  2410. return bool(event.media_urls and event.message_type in batchable)
  2411. def _media_batch_key(self, event: MessageEvent) -> str:
  2412. return f"{self._text_batch_key(event)}:media:{event.message_type.value}"
  2413. @staticmethod
  2414. def _media_batch_is_compatible(existing: MessageEvent, incoming: MessageEvent) -> bool:
  2415. return existing.message_type == incoming.message_type and FeishuAdapter._text_batch_is_compatible(existing, incoming)
  2416. async def _enqueue_media_event(self, event: MessageEvent) -> None:
  2417. key = self._media_batch_key(event)
  2418. existing = self._pending_media_batches.get(key)
  2419. if existing is None:
  2420. self._pending_media_batches[key] = event
  2421. self._schedule_media_batch_flush(key)
  2422. return
  2423. if not self._media_batch_is_compatible(existing, event):
  2424. await self._flush_media_batch_now(key)
  2425. self._pending_media_batches[key] = event
  2426. self._schedule_media_batch_flush(key)
  2427. return
  2428. existing.media_urls.extend(event.media_urls)
  2429. existing.media_types.extend(event.media_types)
  2430. existing.media_text_inlined.extend(event.media_text_inlined)
  2431. if event.text:
  2432. existing.text = self._merge_caption(existing.text, event.text)
  2433. existing.timestamp = event.timestamp
  2434. if event.message_id:
  2435. existing.message_id = event.message_id
  2436. existing.source.message_id = event.message_id
  2437. self._schedule_media_batch_flush(key)
  2438. def _schedule_media_batch_flush(self, key: str) -> None:
  2439. self._reschedule_batch_task(self._pending_media_batch_tasks, key, self._flush_media_batch)
  2440. async def _flush_media_batch(self, key: str) -> None:
  2441. await self._delayed_flush(
  2442. self._pending_media_batch_tasks, key, self._media_batch_delay_seconds, self._flush_media_batch_now,
  2443. )
  2444. @staticmethod
  2445. async def _delayed_flush(task_map: dict[str, asyncio.Task], key: str, delay: float, flush_now: Any) -> None:
  2446. """Sleep ``delay`` then flush; drop our own task handle from ``task_map`` (not a successor's)."""
  2447. current_task = asyncio.current_task()
  2448. try:
  2449. await asyncio.sleep(delay)
  2450. await flush_now(key)
  2451. finally:
  2452. if task_map.get(key) is current_task:
  2453. task_map.pop(key, None)
  2454. async def _flush_media_batch_now(self, key: str) -> None:
  2455. event = self._pending_media_batches.pop(key, None)
  2456. if not event:
  2457. return
  2458. logger.info("[Feishu] Flushing media batch %s with %d attachment(s)", key, len(event.media_urls))
  2459. await self._handle_message_with_guards(event)
  2460. async def _download_remote_image(self, image_url: str) -> str:
  2461. ext = self._guess_remote_extension(image_url, default=".jpg")
  2462. return await cache_image_from_url(image_url, ext=ext)
  2463. async def _download_remote_document(self, file_url: str, *, default_ext: str, preferred_name: str) -> tuple[str, str]:
  2464. from gateway.platforms.base import ssrf_redirect_guard
  2465. from tools.url_safety import create_ssrf_safe_async_client, is_safe_url
  2466. if not is_safe_url(file_url):
  2467. raise ValueError(f"Blocked unsafe URL (SSRF protection): {file_url[:80]}")
  2468. async with create_ssrf_safe_async_client(
  2469. timeout=30.0, follow_redirects=True, event_hooks={"response": [ssrf_redirect_guard]},
  2470. ) as client:
  2471. response = await client.get(
  2472. file_url, headers={"User-Agent": "Mozilla/5.0 (compatible; HermesAgent/1.0)", "Accept": "*/*"},
  2473. )
  2474. response.raise_for_status()
  2475. # Snapshot headers + body inside the context so pooled connections fully release.
  2476. # See #18451.
  2477. content_type_hdr = str(response.headers.get("Content-Type", ""))
  2478. body = response.content
  2479. filename = self._derive_remote_filename(
  2480. file_url, content_type=content_type_hdr, default_name=preferred_name, default_ext=default_ext,
  2481. )
  2482. return await cache_document_from_bytes_async(body, filename), filename
  2483. @staticmethod
  2484. def _guess_remote_extension(url: str, *, default: str) -> str:
  2485. ext = Path((url or "").split("?", 1)[0]).suffix.lower()
  2486. return ext if ext in (_IMAGE_EXTENSIONS | _AUDIO_EXTENSIONS | _VIDEO_EXTENSIONS | set(SUPPORTED_DOCUMENT_TYPES)) else default
  2487. @staticmethod
  2488. def _derive_remote_filename(file_url: str, *, content_type: str, default_name: str, default_ext: str) -> str:
  2489. candidate = Path((file_url or "").split("?", 1)[0]).name or default_name
  2490. ext = Path(candidate).suffix.lower()
  2491. if not ext:
  2492. guessed = mimetypes.guess_extension((content_type or "").split(";", 1)[0].strip().lower() or "") or default_ext
  2493. candidate = f"{candidate}{guessed}"
  2494. return candidate
  2495. @staticmethod
  2496. def _namespace_from_mapping(value: Any) -> Any:
  2497. if isinstance(value, dict):
  2498. return SimpleNamespace(**{key: FeishuAdapter._namespace_from_mapping(item) for key, item in value.items()})
  2499. if isinstance(value, list):
  2500. return [FeishuAdapter._namespace_from_mapping(item) for item in value]
  2501. return value
  2502. def _webhook_reject(self, remote_ip: str, anomaly: str, status: int, text: Optional[str] = None,
  2503. json_msg: Optional[str] = None) -> Any:
  2504. """Record an anomaly for ``remote_ip`` and build the matching aiohttp error response."""
  2505. self._record_webhook_anomaly(remote_ip, anomaly)
  2506. if json_msg is not None:
  2507. return web.json_response({"code": status, "msg": json_msg}, status=status)
  2508. return web.Response(status=status, text=text)
  2509. async def _handle_webhook_request(self, request: Any) -> Any:
  2510. remote_ip = (getattr(request, "remote", None) or "unknown")
  2511. # Rate-limit key is app_id:path:remote_ip (matches openclaw key structure).
  2512. if not self._check_webhook_rate_limit(f"{self._app_id}:{self._webhook_path}:{remote_ip}"):
  2513. logger.warning("[Feishu] Webhook rate limit exceeded for %s", remote_ip)
  2514. return self._webhook_reject(remote_ip, "429", 429, "Too Many Requests")
  2515. headers = getattr(request, "headers", {}) or {}
  2516. content_type = str(headers.get("Content-Type", "") or "").split(";")[0].strip().lower()
  2517. if content_type and content_type != "application/json": # Feishu always sends JSON
  2518. logger.warning("[Feishu] Webhook rejected: unexpected Content-Type %r from %s", content_type, remote_ip)
  2519. return self._webhook_reject(remote_ip, "415", 415, "Unsupported Media Type")
  2520. content_length = getattr(request, "content_length", None)
  2521. if content_length is not None and content_length > _FEISHU_WEBHOOK_MAX_BODY_BYTES:
  2522. logger.warning("[Feishu] Webhook body too large (%d bytes) from %s", content_length, remote_ip)
  2523. return self._webhook_reject(remote_ip, "413", 413, "Request body too large")
  2524. try:
  2525. body_bytes: bytes = await asyncio.wait_for(
  2526. _read_limited_feishu_webhook_body(request, _FEISHU_WEBHOOK_MAX_BODY_BYTES),
  2527. timeout=_FEISHU_WEBHOOK_BODY_TIMEOUT_SECONDS,
  2528. )
  2529. except ValueError:
  2530. logger.warning("[Feishu] Webhook body exceeds limit from %s", remote_ip)
  2531. return self._webhook_reject(remote_ip, "413", 413, "Request body too large")
  2532. except TimeoutError:
  2533. logger.warning("[Feishu] Webhook body read timed out after %ds from %s", _FEISHU_WEBHOOK_BODY_TIMEOUT_SECONDS, remote_ip)
  2534. return self._webhook_reject(remote_ip, "408", 408, "Request Timeout")
  2535. except Exception:
  2536. return self._webhook_reject(remote_ip, "400", 400, json_msg="failed to read body")
  2537. try:
  2538. payload = json.loads(body_bytes.decode("utf-8"))
  2539. except (json.JSONDecodeError, UnicodeDecodeError):
  2540. return self._webhook_reject(remote_ip, "400", 400, json_msg="invalid json")
  2541. # Verification token: second defence layer beyond the signature (matches openclaw).
  2542. if self._verification_token:
  2543. header = payload.get("header") or {}
  2544. incoming_token = str(header.get("token") or payload.get("token") or "")
  2545. # compare_digest as bytes — it raises TypeError on non-ASCII str, and the token is remote input.
  2546. if not incoming_token or not hmac.compare_digest(
  2547. incoming_token.encode(), self._verification_token.encode()
  2548. ):
  2549. logger.warning("[Feishu] Webhook rejected: invalid verification token from %s", remote_ip)
  2550. return self._webhook_reject(remote_ip, "401-token", 401, "Invalid verification token")
  2551. # Token is validated above BEFORE reflecting the challenge, so an unauthenticated
  2552. # remote can't prove endpoint control by getting its own challenge echoed back.
  2553. if payload.get("type") == "url_verification":
  2554. return web.json_response({"challenge": payload.get("challenge", "")})
  2555. if self._encrypt_key and not self._is_webhook_signature_valid(request.headers, body_bytes):
  2556. logger.warning("[Feishu] Webhook rejected: invalid signature from %s", remote_ip)
  2557. return self._webhook_reject(remote_ip, "401-sig", 401, "Invalid signature")
  2558. if payload.get("encrypt"):
  2559. logger.error("[Feishu] Encrypted webhook payloads are not supported by Hermes webhook mode")
  2560. return self._webhook_reject(
  2561. remote_ip, "400-encrypted", 400, json_msg="encrypted webhook payloads are not supported",
  2562. )
  2563. self._clear_webhook_anomaly(remote_ip)
  2564. event_type = str((payload.get("header") or {}).get("event_type") or "")
  2565. if event_type == "card.action.trigger":
  2566. return web.json_response(self._on_webhook_card_action(payload))
  2567. data = self._namespace_from_mapping(payload)
  2568. if event_type in {"im.message.reaction.created_v1", "im.message.reaction.deleted_v1"}:
  2569. self._on_reaction_event(event_type, data)
  2570. else:
  2571. handler = self._WEBHOOK_EVENT_HANDLERS.get(event_type)
  2572. if handler is None:
  2573. logger.debug("[Feishu] Ignoring webhook event type: %s", event_type or "unknown")
  2574. else:
  2575. getattr(self, handler)(data)
  2576. return web.json_response({"code": 0, "msg": "ok"})
  2577. # Webhook event_type -> handler method name (reaction events are routed separately).
  2578. _WEBHOOK_EVENT_HANDLERS = {
  2579. "im.message.receive_v1": "_on_message_event",
  2580. "im.message.message_read_v1": "_on_message_read_event",
  2581. "im.chat.member.bot.added_v1": "_on_bot_added_to_chat",
  2582. "im.chat.member.bot.deleted_v1": "_on_bot_removed_from_chat",
  2583. "drive.notice.comment_add_v1": "_on_drive_comment_event",
  2584. "vc.bot.meeting_invited_v1": "_on_meeting_invited_event",
  2585. }
  2586. def _is_webhook_signature_valid(self, headers: Any, body_bytes: bytes) -> bool:
  2587. """Timing-safe check of x-lark-signature == SHA256(timestamp + nonce + encrypt_key + body)."""
  2588. timestamp, nonce, signature = (
  2589. str(headers.get(name, "") or "")
  2590. for name in ("x-lark-request-timestamp", "x-lark-request-nonce", "x-lark-signature")
  2591. )
  2592. if not timestamp or not nonce or not signature:
  2593. return False
  2594. try:
  2595. body_str = body_bytes.decode("utf-8", errors="replace")
  2596. computed = hashlib.sha256(f"{timestamp}{nonce}{self._encrypt_key}{body_str}".encode()).hexdigest()
  2597. # Compare as bytes: compare_digest raises TypeError on non-ASCII str, and the header is remote input.
  2598. return hmac.compare_digest(computed.encode(), signature.encode())
  2599. except Exception:
  2600. logger.debug("[Feishu] Signature verification raised an exception", exc_info=True)
  2601. return False
  2602. def _check_webhook_rate_limit(self, rate_key: str) -> bool:
  2603. """Sliding-window limiter keyed by "{app_id}:{path}:{remote_ip}" (openclaw); table capped, fail-closed."""
  2604. now = time.time()
  2605. entry = self._webhook_rate_counts.get(rate_key)
  2606. if entry is not None:
  2607. count, window_start = entry
  2608. if now - window_start < _FEISHU_WEBHOOK_RATE_WINDOW_SECONDS:
  2609. if count >= _FEISHU_WEBHOOK_RATE_LIMIT_MAX:
  2610. return False
  2611. self._webhook_rate_counts[rate_key] = (count + 1, window_start)
  2612. return True
  2613. # New window or new key — prune stale entries when at capacity.
  2614. if len(self._webhook_rate_counts) >= _FEISHU_WEBHOOK_RATE_MAX_KEYS:
  2615. for k in [k for k, (_, ws) in self._webhook_rate_counts.items() if now - ws >= _FEISHU_WEBHOOK_RATE_WINDOW_SECONDS]:
  2616. del self._webhook_rate_counts[k]
  2617. # Still full → deny untracked keys (fail closed): the table only fills this far under
  2618. # abuse, and letting untracked requests through would bypass the limiter entirely.
  2619. if rate_key not in self._webhook_rate_counts and len(self._webhook_rate_counts) >= _FEISHU_WEBHOOK_RATE_MAX_KEYS:
  2620. logger.warning(
  2621. "[Feishu] Webhook rate-limit table at capacity (%d keys) — denying untracked key",
  2622. _FEISHU_WEBHOOK_RATE_MAX_KEYS,
  2623. )
  2624. return False
  2625. self._webhook_rate_counts[rate_key] = (1, now)
  2626. return True
  2627. # --- Text batching ---
  2628. @staticmethod
  2629. def _text_batch_is_compatible(existing: MessageEvent, incoming: MessageEvent) -> bool:
  2630. """Only merge text events when reply/thread context is identical."""
  2631. return (
  2632. existing.reply_to_message_id == incoming.reply_to_message_id
  2633. and existing.reply_to_text == incoming.reply_to_text
  2634. and existing.source.thread_id == incoming.source.thread_id
  2635. )
  2636. async def _enqueue_text_event(self, event: MessageEvent) -> None:
  2637. """Debounce rapid Feishu text bursts into a single MessageEvent."""
  2638. key = self._text_batch_key(event)
  2639. chunk_len = len(event.text or "")
  2640. def _start_batch() -> None:
  2641. self._pending_text_batches[key] = event
  2642. self._pending_text_batch_counts[key] = 1
  2643. self._schedule_text_batch_flush(key)
  2644. existing = self._pending_text_batches.get(key)
  2645. if existing is None:
  2646. event._last_chunk_len = chunk_len # type: ignore[attr-defined]
  2647. _start_batch()
  2648. return
  2649. if not self._text_batch_is_compatible(existing, event):
  2650. await self._flush_text_batch_now(key)
  2651. _start_batch()
  2652. return
  2653. next_count = self._pending_text_batch_counts.get(key, 1) + 1
  2654. appended_text = event.text or ""
  2655. next_text = f"{existing.text}\n{appended_text}" if existing.text and appended_text else (existing.text or appended_text)
  2656. if next_count > self._text_batch_max_messages or len(next_text) > self._text_batch_max_chars:
  2657. await self._flush_text_batch_now(key)
  2658. _start_batch()
  2659. return
  2660. existing.text = next_text
  2661. existing.media_urls.extend(event.media_urls)
  2662. existing.media_types.extend(event.media_types)
  2663. existing.media_text_inlined.extend(event.media_text_inlined)
  2664. existing._last_chunk_len = chunk_len # type: ignore[attr-defined]
  2665. existing.timestamp = event.timestamp
  2666. if event.message_id:
  2667. existing.message_id = event.message_id
  2668. existing.source.message_id = event.message_id
  2669. self._pending_text_batch_counts[key] = next_count
  2670. self._schedule_text_batch_flush(key)
  2671. def _schedule_text_batch_flush(self, key: str) -> None:
  2672. """Reset the debounce timer for a pending Feishu text batch."""
  2673. self._reschedule_batch_task(self._pending_text_batch_tasks, key, self._flush_text_batch)
  2674. @staticmethod
  2675. def _reschedule_batch_task(task_map: dict[str, asyncio.Task], key: str, flush_fn: Any) -> None:
  2676. prior_task = task_map.get(key)
  2677. if prior_task and not prior_task.done():
  2678. prior_task.cancel()
  2679. task_map[key] = asyncio.create_task(flush_fn(key))
  2680. def _pop_text_batch(self, key: str) -> Optional[MessageEvent]:
  2681. self._pending_text_batch_counts.pop(key, None)
  2682. return self._pending_text_batches.pop(key, None)
  2683. async def _dispatch_text_batch(self, event: MessageEvent) -> None:
  2684. await self._handle_message_with_guards(event)
  2685. # --- Message content extraction and resource download ---
  2686. def _normalize(self, message_type: Any, raw_content: Any, mentions: Any) -> FeishuNormalizedMessage:
  2687. return normalize_feishu_message(
  2688. message_type=message_type, raw_content=raw_content, mentions=mentions, bot=self._bot_identity(),
  2689. )
  2690. async def _extract_message_content(
  2691. self, message: Any
  2692. ) -> tuple[str, MessageType, list[str], list[str], list[bool], list[FeishuMentionRef]]:
  2693. raw_content = getattr(message, "content", "") or ""
  2694. raw_type = getattr(message, "message_type", "") or ""
  2695. message_id = str(getattr(message, "message_id", "") or "")
  2696. logger.info("[Feishu] Received raw message type=%s message_id=%s", raw_type, message_id)
  2697. normalized = self._normalize(raw_type, raw_content, getattr(message, "mentions", None))
  2698. media_urls, media_types = await self._download_feishu_message_resources(
  2699. message_id=message_id, normalized=normalized,
  2700. )
  2701. inbound_type = self._resolve_normalized_message_type(normalized, media_types)
  2702. text = normalized.text_content
  2703. media_text_inlined: list[bool] = []
  2704. inlined_parts: list[str] = []
  2705. for media_url, media_type in zip(media_urls, media_types):
  2706. extracted = await self._maybe_extract_text_document(media_url, media_type)
  2707. media_text_inlined.append(bool(extracted))
  2708. if extracted:
  2709. inlined_parts.append(extracted)
  2710. if inlined_parts:
  2711. extracted_text = "\n\n".join(inlined_parts)
  2712. text = f"{text}\n\n{extracted_text}" if text else extracted_text
  2713. return text, inbound_type, media_urls, media_types, media_text_inlined, list(normalized.mentions)
  2714. async def _download_feishu_message_resources(
  2715. self, *, message_id: str, normalized: FeishuNormalizedMessage,
  2716. ) -> tuple[list[str], list[str]]:
  2717. media_urls: list[str] = []
  2718. media_types: list[str] = []
  2719. def _collect(cached_path: str, media_type: str) -> None:
  2720. if cached_path:
  2721. media_urls.append(cached_path)
  2722. media_types.append(media_type)
  2723. for image_key in normalized.image_keys:
  2724. _collect(*await self._download_feishu_image(message_id=message_id, image_key=image_key))
  2725. for ref in normalized.media_refs:
  2726. _collect(*await self._download_feishu_message_resource(
  2727. message_id=message_id, file_key=ref.file_key, resource_type=ref.resource_type,
  2728. fallback_filename=ref.file_name,
  2729. ))
  2730. return media_urls, media_types
  2731. @staticmethod
  2732. def _resolve_media_message_type(media_type: str, *, default: MessageType) -> MessageType:
  2733. normalized = (media_type or "").lower()
  2734. if normalized.startswith("image/"):
  2735. return MessageType.PHOTO
  2736. if normalized.startswith("audio/"):
  2737. return MessageType.AUDIO
  2738. if normalized.startswith("video/"):
  2739. return MessageType.VIDEO
  2740. return default
  2741. def _resolve_normalized_message_type(self, normalized: FeishuNormalizedMessage, media_types: list[str]) -> MessageType:
  2742. preferred = normalized.preferred_message_type
  2743. if preferred == "audio":
  2744. # Lark's native "audio" is an in-app voice recording (uploaded audio arrives as
  2745. # file/media → "document"). VOICE makes the gateway auto-transcribe it like
  2746. # Discord/DingTalk/Telegram; as AUDIO it would be silently ignored.
  2747. # Classify it as VOICE so the gateway auto-transcribes it (Opus → STT) the same way
  2748. # Discord/DingTalk/Telegram/etc. do — otherwise a Feishu voice note reaches the agent as an
  2749. # untranscribable AUDIO attachment and is silently ignored. Follow-up to #28993, which added
  2750. # native voice-note transcription for Discord + DingTalk.
  2751. return MessageType.VOICE
  2752. if preferred in ("photo", "document"):
  2753. default = MessageType.PHOTO if preferred == "photo" else MessageType.DOCUMENT
  2754. return self._resolve_media_message_type(media_types[0] if media_types else "", default=default)
  2755. return MessageType.TEXT
  2756. async def _maybe_extract_text_document(self, cached_path: str, media_type: str) -> str:
  2757. if not cached_path or not media_type.startswith("text/"):
  2758. return ""
  2759. try:
  2760. if os.path.getsize(cached_path) > _MAX_TEXT_INJECT_BYTES:
  2761. return ""
  2762. ext = Path(cached_path).suffix.lower()
  2763. if ext not in {".txt", ".md"} and media_type not in {"text/plain", "text/markdown"}:
  2764. return ""
  2765. content = Path(cached_path).read_text(encoding="utf-8-sig")
  2766. display_name = self._display_name_from_cached_path(cached_path)
  2767. return f"[Content of {display_name}]:\n{content}"
  2768. except (OSError, UnicodeDecodeError):
  2769. logger.warning("[Feishu] Failed to inject text document content from %s", cached_path, exc_info=True)
  2770. return ""
  2771. async def _fetch_message_resource(self, *, message_id: str, file_key: str, resource_type: str) -> Any:
  2772. """GET im/v1/messages/{id}/resources/{key}; returns the SDK response (caller checks success)."""
  2773. request = self._build_message_resource_request(
  2774. message_id=message_id, file_key=file_key, resource_type=resource_type,
  2775. )
  2776. return await self._run_blocking(self._client.im.v1.message_resource.get, request)
  2777. async def _download_feishu_image(self, *, message_id: str, image_key: str) -> tuple[str, str]:
  2778. if not self._client or not message_id:
  2779. return "", ""
  2780. try:
  2781. response = await self._fetch_message_resource(message_id=message_id, file_key=image_key, resource_type="image")
  2782. if not response or not response.success():
  2783. logger.warning(
  2784. "[Feishu] Failed to download image %s: %s %s",
  2785. image_key, getattr(response, "code", "unknown"), getattr(response, "msg", "request failed"),
  2786. )
  2787. return "", ""
  2788. raw_bytes = self._read_binary_response(response)
  2789. if not raw_bytes:
  2790. return "", ""
  2791. content_type = self._get_response_header(response, "Content-Type")
  2792. filename = getattr(response, "file_name", None) or f"{image_key}.jpg"
  2793. ext = self._guess_extension(filename, content_type, ".jpg", allowed=_IMAGE_EXTENSIONS)
  2794. cached_path = await cache_image_from_bytes_async(raw_bytes, ext=ext)
  2795. return cached_path, self._normalize_media_type(content_type, default=self._default_image_media_type(ext))
  2796. except Exception:
  2797. logger.warning("[Feishu] Failed to cache image resource %s", image_key, exc_info=True)
  2798. return "", ""
  2799. async def _download_feishu_message_resource(
  2800. self, *, message_id: str, file_key: str, resource_type: str, fallback_filename: str,
  2801. ) -> tuple[str, str]:
  2802. if not self._client or not message_id:
  2803. return "", ""
  2804. # audio/media uploads are sometimes only retrievable as type=file.
  2805. request_types = [resource_type] + (["file"] if resource_type in {"audio", "media"} else [])
  2806. for request_type in request_types:
  2807. try:
  2808. response = await self._fetch_message_resource(
  2809. message_id=message_id, file_key=file_key, resource_type=request_type,
  2810. )
  2811. if not response or not response.success():
  2812. logger.debug(
  2813. "[Feishu] Resource download failed for %s/%s via type=%s: %s %s",
  2814. message_id, file_key, request_type,
  2815. getattr(response, "code", "unknown"), getattr(response, "msg", "request failed"),
  2816. )
  2817. continue
  2818. raw_bytes = self._read_binary_response(response)
  2819. if not raw_bytes:
  2820. continue
  2821. content_type = self._get_response_header(response, "Content-Type")
  2822. filename = (getattr(response, "file_name", None) or "") or fallback_filename or f"{request_type}_{file_key}"
  2823. media_type = self._normalize_media_type(
  2824. content_type, default=self._guess_media_type_from_filename(filename),
  2825. )
  2826. if media_type.startswith("image/"):
  2827. ext = self._guess_extension(filename, content_type, ".jpg", allowed=_IMAGE_EXTENSIONS)
  2828. kind, cached_path = "image", await cache_image_from_bytes_async(raw_bytes, ext=ext)
  2829. media_type = media_type or self._default_image_media_type(ext)
  2830. elif request_type == "audio" or media_type.startswith("audio/"):
  2831. ext = self._guess_extension(filename, content_type, ".ogg", allowed=_AUDIO_EXTENSIONS)
  2832. kind, cached_path = "audio", await cache_audio_from_bytes_async(raw_bytes, ext=ext)
  2833. media_type = media_type or f"audio/{ext.lstrip('.') or 'ogg'}"
  2834. elif media_type.startswith("video/"):
  2835. if not Path(filename).suffix:
  2836. filename = f"{filename}.mp4"
  2837. kind, cached_path = "video", await cache_document_from_bytes_async(raw_bytes, filename)
  2838. else:
  2839. if not Path(filename).suffix and media_type in _DOCUMENT_MIME_TO_EXT:
  2840. filename = f"{filename}{_DOCUMENT_MIME_TO_EXT[media_type]}"
  2841. kind, cached_path = "document", await cache_document_from_bytes_async(raw_bytes, filename)
  2842. media_type = media_type or self._guess_document_media_type(filename)
  2843. logger.info("[Feishu] Cached message %s resource at %s", kind, cached_path)
  2844. return cached_path, media_type
  2845. except Exception:
  2846. logger.warning("[Feishu] Failed to cache message resource %s/%s", message_id, file_key, exc_info=True)
  2847. return "", ""
  2848. # --- Static helpers — extension / media-type guessing ---
  2849. @staticmethod
  2850. def _read_binary_response(response: Any) -> bytes:
  2851. file_obj = getattr(response, "file", None)
  2852. if file_obj is None:
  2853. return b""
  2854. if hasattr(file_obj, "getvalue"):
  2855. return bytes(file_obj.getvalue())
  2856. return bytes(file_obj.read())
  2857. @staticmethod
  2858. def _get_response_header(response: Any, name: str) -> str:
  2859. raw = getattr(response, "raw", None)
  2860. headers = getattr(raw, "headers", {}) or {}
  2861. return str(headers.get(name, headers.get(name.lower(), "")) or "").split(";", 1)[0].strip().lower()
  2862. @staticmethod
  2863. def _guess_extension(filename: str, content_type: str, default: str, *, allowed: set[str]) -> str:
  2864. ext = Path(filename or "").suffix.lower()
  2865. if ext in allowed:
  2866. return ext
  2867. guessed = mimetypes.guess_extension((content_type or "").split(";", 1)[0].strip().lower() or "")
  2868. return guessed if guessed in allowed else default
  2869. @staticmethod
  2870. def _normalize_media_type(content_type: str, *, default: str) -> str:
  2871. normalized = (content_type or "").split(";", 1)[0].strip().lower()
  2872. return normalized or default
  2873. @staticmethod
  2874. def _guess_document_media_type(filename: str) -> str:
  2875. ext = Path(filename or "").suffix.lower()
  2876. return SUPPORTED_DOCUMENT_TYPES.get(ext, mimetypes.guess_type(filename or "")[0] or "application/octet-stream")
  2877. @staticmethod
  2878. def _display_name_from_cached_path(path: str) -> str:
  2879. basename = os.path.basename(path)
  2880. parts = basename.split("_", 2)
  2881. display_name = parts[2] if len(parts) >= 3 else basename
  2882. return re.sub(r"[^\w.\- ]", "_", display_name)
  2883. @staticmethod
  2884. def _guess_media_type_from_filename(filename: str) -> str:
  2885. guessed = (mimetypes.guess_type(filename or "")[0] or "").lower()
  2886. if guessed:
  2887. return guessed
  2888. ext = Path(filename or "").suffix.lower()
  2889. if ext in _VIDEO_EXTENSIONS:
  2890. return f"video/{ext.lstrip('.')}"
  2891. if ext in _AUDIO_EXTENSIONS:
  2892. return f"audio/{ext.lstrip('.')}"
  2893. if ext in _IMAGE_EXTENSIONS:
  2894. return FeishuAdapter._default_image_media_type(ext)
  2895. return ""
  2896. @staticmethod
  2897. def _map_chat_type(raw_chat_type: str) -> str:
  2898. normalized = (raw_chat_type or "").strip().lower()
  2899. if normalized == "p2p":
  2900. return "dm"
  2901. if any(marker in normalized for marker in ("topic", "thread", "forum")):
  2902. return "forum"
  2903. return "group" if normalized == "group" else "dm"
  2904. @staticmethod
  2905. def _resolve_source_chat_type(*, chat_info: dict[str, Any], event_chat_type: str) -> str:
  2906. resolved = str(chat_info.get("type") or "").strip().lower()
  2907. if resolved in {"group", "forum"}:
  2908. return resolved
  2909. return "dm" if event_chat_type == "p2p" else "group"
  2910. async def _resolve_sender_profile(self, sender_id: Any, *, is_bot: bool = False) -> dict[str, Optional[str]]:
  2911. """Map Feishu's ID tiers onto SessionSource: user_id (tenant) > open_id (app) as primary,
  2912. union_id (developer-scoped, cross-app stable) as user_id_alt — session keys prefer the alt."""
  2913. open_id = getattr(sender_id, "open_id", None) or None
  2914. user_id = getattr(sender_id, "user_id", None) or None
  2915. union_id = getattr(sender_id, "union_id", None) or None
  2916. primary_id = user_id or open_id
  2917. name_lookup_id = open_id if is_bot else (primary_id or union_id) # bots/basic_batch only takes open_id
  2918. display_name = await self._resolve_sender_name_from_api(name_lookup_id, is_bot=is_bot)
  2919. return {"user_id": primary_id, "user_name": display_name, "user_id_alt": union_id}
  2920. def _get_cached_sender_name(self, sender_id: Optional[str]) -> Optional[str]:
  2921. """Return a cached sender name only while its TTL is still valid."""
  2922. cached = self._sender_name_cache.get(sender_id) if sender_id else None
  2923. if cached is None:
  2924. return None
  2925. name, expire_at = cached
  2926. if time.time() < expire_at:
  2927. return name
  2928. self._sender_name_cache.pop(sender_id, None)
  2929. return None
  2930. async def _resolve_sender_name_from_api(self, sender_id: Optional[str], *, is_bot: bool = False) -> Optional[str]:
  2931. """Bots go via bot/basic_batch (contact API has no bot names). Failures are silent — never block the pipeline."""
  2932. trimmed = sender_id.strip() if sender_id and self._client else ""
  2933. if not trimmed:
  2934. return None
  2935. now = time.time()
  2936. cached_name = self._get_cached_sender_name(trimmed)
  2937. if cached_name is not None:
  2938. return cached_name or None # "" cached means "known nameless"
  2939. if is_bot:
  2940. names = await self._fetch_bot_names([trimmed])
  2941. if names is None:
  2942. return None
  2943. for oid, name in names.items():
  2944. self._sender_name_cache[oid] = (name, now + _FEISHU_SENDER_NAME_TTL_SECONDS)
  2945. hit = self._sender_name_cache.get(trimmed)
  2946. return (hit[0] or None) if hit else None
  2947. try:
  2948. from lark_oapi.api.contact.v3 import GetUserRequest # lazy import
  2949. id_type = "open_id" if trimmed.startswith("ou_") else "union_id" if trimmed.startswith("on_") else "user_id"
  2950. request = GetUserRequest.builder().user_id(trimmed).user_id_type(id_type).build()
  2951. response = await self._run_blocking(self._client.contact.v3.user.get, request)
  2952. if not response or not response.success():
  2953. return None
  2954. user = getattr(getattr(response, "data", None), "user", None)
  2955. candidates = (getattr(user, k, None) for k in ("name", "display_name", "nickname", "en_name"))
  2956. name = next((value for value in candidates if value), None)
  2957. if name and isinstance(name, str) and name.strip():
  2958. name = name.strip()
  2959. self._sender_name_cache[trimmed] = (name, now + _FEISHU_SENDER_NAME_TTL_SECONDS)
  2960. return name
  2961. except Exception:
  2962. logger.debug("[Feishu] Failed to resolve sender name for %s", sender_id, exc_info=True)
  2963. return None
  2964. async def _tenant_get_raw(self, uri: str, *, queries: Optional[list[tuple[str, str]]] = None) -> Any:
  2965. """GET ``uri`` with the tenant token via the raw client; returns the raw response content."""
  2966. resp = await self._run_blocking(self._client.request, _tenant_get_request(uri, queries=queries))
  2967. return getattr(getattr(resp, "raw", None), "content", None)
  2968. async def _fetch_bot_names(self, bot_ids: list[str]) -> Optional[dict[str, str]]:
  2969. if not self._client or not bot_ids:
  2970. return None
  2971. try:
  2972. content = await self._tenant_get_raw(
  2973. "/open-apis/bot/v3/bots/basic_batch", queries=[("bot_ids", oid) for oid in bot_ids],
  2974. )
  2975. if not content:
  2976. return None
  2977. payload = json.loads(content)
  2978. if payload.get("code") != 0:
  2979. return None
  2980. bots = (payload.get("data") or {}).get("bots") or {}
  2981. return {oid: str(info.get("name") or "").strip() for oid, info in bots.items() if oid}
  2982. except Exception:
  2983. logger.debug("[Feishu] Failed to fetch bot names for %s", bot_ids, exc_info=True)
  2984. return None
  2985. async def _fetch_message_text(self, message_id: str) -> Optional[str]:
  2986. if not self._client or not message_id:
  2987. return None
  2988. if message_id in self._message_text_cache:
  2989. self._message_text_cache.move_to_end(message_id)
  2990. return self._message_text_cache[message_id]
  2991. try:
  2992. request = self._build_get_message_request(message_id)
  2993. response = await self._run_blocking(self._client.im.v1.message.get, request)
  2994. if not response or getattr(response, "success", lambda: False)() is False:
  2995. code = getattr(response, "code", "unknown")
  2996. msg = getattr(response, "msg", "message lookup failed")
  2997. logger.warning("[Feishu] Failed to fetch parent message %s: [%s] %s", message_id, code, msg)
  2998. return None
  2999. items = getattr(getattr(response, "data", None), "items", None) or []
  3000. parent = items[0] if items else None
  3001. body = getattr(parent, "body", None)
  3002. msg_type = getattr(parent, "msg_type", "") or ""
  3003. raw_content = getattr(body, "content", "") or ""
  3004. parent_mentions = getattr(parent, "mentions", None) if parent else None
  3005. text = self._extract_text_from_raw_content(
  3006. msg_type=msg_type, raw_content=raw_content, mentions=parent_mentions,
  3007. )
  3008. self._message_text_cache[message_id] = text
  3009. while len(self._message_text_cache) > _FEISHU_MESSAGE_TEXT_CACHE_SIZE:
  3010. self._message_text_cache.popitem(last=False)
  3011. return text
  3012. except Exception:
  3013. logger.warning("[Feishu] Failed to fetch parent message %s", message_id, exc_info=True)
  3014. return None
  3015. def _extract_text_from_raw_content(
  3016. self, *, msg_type: str, raw_content: str, mentions: Optional[Sequence[Any]] = None,
  3017. ) -> Optional[str]:
  3018. normalized = self._normalize(msg_type, raw_content, mentions)
  3019. if normalized.text_content:
  3020. return normalized.text_content
  3021. placeholder = normalized.metadata.get("placeholder_text") if isinstance(normalized.metadata, dict) else None
  3022. return str(placeholder).strip() or None
  3023. @staticmethod
  3024. def _default_image_media_type(ext: str) -> str:
  3025. normalized_ext = (ext or "").lower()
  3026. if normalized_ext in {".jpg", ".jpeg"}:
  3027. return "image/jpeg"
  3028. return f"image/{normalized_ext.lstrip('.') or 'jpeg'}"
  3029. @staticmethod
  3030. def _log_background_failure(future: Any) -> None:
  3031. try:
  3032. future.result()
  3033. except Exception:
  3034. logger.exception("[Feishu] Background inbound processing failed")
  3035. # --- Inbound admission ---
  3036. def _admit(self, sender: Any, message: Any) -> Optional[RejectReason]:
  3037. sender_ids = _sender_identity(sender)
  3038. self_ids = frozenset(v for v in (self._bot_open_id, self._bot_user_id) if v)
  3039. is_bot = _is_bot_sender(sender)
  3040. is_group = getattr(message, "chat_type", "p2p") != "p2p"
  3041. chat_id = getattr(message, "chat_id", "") or ""
  3042. require_mention = is_group and self._require_mention_for(chat_id)
  3043. # Defensive only — Feishu doesn't echo our outbound back as inbound,
  3044. # and open_id is always populated on both sides.
  3045. if self_ids and sender_ids & self_ids:
  3046. return "self_echo"
  3047. if is_bot:
  3048. mode = self._allow_bots
  3049. if mode not in ("mentions", "all"):
  3050. return "bots_disabled"
  3051. if not self_ids or not sender_ids: # pre-hydration or malformed payloads
  3052. return "self_ids_unknown"
  3053. # The group step below enforces mentions when require_mention is on; cover the rest here.
  3054. if mode == "mentions" and not require_mention and not self._mentions_self(message):
  3055. return "bot_not_mentioned"
  3056. if not is_group:
  3057. # _allow_all_dm is snapshotted per-profile in _load_settings: _admit runs on the
  3058. # lark_oapi WS thread with no secret scope, so a bare os.getenv would read the
  3059. # default profile's value.
  3060. # Empty FEISHU_ALLOWED_USERS is setup's pairing-mode default: forward DMs so the
  3061. # pairing handshake can run (gateway auth fail-closes until approval).
  3062. if self._allow_all_dm or not self._allowed_group_users:
  3063. return None
  3064. return None if sender_ids & self._allowed_group_users else "dm_policy_rejected"
  3065. if not self._allow_group_message(getattr(sender, "sender_id", None), chat_id, is_bot=is_bot):
  3066. return "group_policy_rejected"
  3067. if require_mention and not self._mentions_self(message):
  3068. return "group_policy_rejected"
  3069. return None
  3070. # Class default so the first drop after construction is the one that warns.
  3071. _warned_empty_allowlist_deny = False
  3072. def _warn_once_empty_allowlist_deny(self, chat_id: str) -> None:
  3073. """One WARNING when group traffic dies on the untouched allowlist default (#111420).
  3074. The policy read is scoped per profile on purpose — never inherit another profile's
  3075. FEISHU_GROUP_POLICY here; only make the resulting deny visible above DEBUG.
  3076. """
  3077. if self._warned_empty_allowlist_deny:
  3078. return
  3079. from plugins.platforms.feishu.feishu_admission_diagnostics import empty_allowlist_drop_warning
  3080. text = empty_allowlist_drop_warning(
  3081. chat_id=chat_id, group_rules=self._group_rules,
  3082. default_group_policy=self._default_group_policy, allowed_group_users=self._allowed_group_users,
  3083. )
  3084. if text:
  3085. self._warned_empty_allowlist_deny = True
  3086. logger.warning(text)
  3087. def _require_mention_for(self, chat_id: str) -> bool:
  3088. rule = self._group_rules.get(chat_id) if chat_id else None
  3089. if rule and rule.require_mention is not None:
  3090. return rule.require_mention
  3091. return self._require_mention
  3092. def _allow_group_message(self, sender_id: Any, chat_id: str = "", *, is_bot: bool = False) -> bool:
  3093. """Per-group policy gate for non-DM traffic."""
  3094. sender_ids = {getattr(sender_id, "open_id", None), getattr(sender_id, "user_id", None)} - {None}
  3095. if sender_ids and self._admins and (sender_ids & self._admins):
  3096. return True
  3097. rule = self._group_rules.get(chat_id) if chat_id else None
  3098. if rule:
  3099. policy, allowlist, blacklist = rule.policy, rule.allowlist, rule.blacklist
  3100. else:
  3101. policy, allowlist, blacklist = self._default_group_policy or self._group_policy, self._allowed_group_users, set()
  3102. # Channel locks apply to everyone; allowlist/blacklist only gate humans (bots were
  3103. # already cleared upstream by FEISHU_ALLOW_BOTS).
  3104. if policy in ("disabled", "admin_only"):
  3105. return False
  3106. if policy == "open" or is_bot:
  3107. return True
  3108. if policy == "allowlist":
  3109. return bool(sender_ids and (sender_ids & allowlist))
  3110. if policy == "blacklist":
  3111. return bool(sender_ids and not (sender_ids & blacklist))
  3112. return bool(sender_ids and (sender_ids & self._allowed_group_users))
  3113. def _mentions_self(self, message: Any) -> bool:
  3114. # @_all is Feishu's @everyone placeholder.
  3115. raw_content = getattr(message, "content", "") or ""
  3116. if "@_all" in raw_content:
  3117. return True
  3118. mentions = getattr(message, "mentions", None) or []
  3119. if mentions and self._message_mentions_bot(mentions):
  3120. return True
  3121. normalized = self._normalize(getattr(message, "message_type", "") or "", raw_content, getattr(message, "mentions", None))
  3122. return self._post_mentions_bot(normalized.mentions)
  3123. def _message_mentions_bot(self, mentions: list[Any]) -> bool:
  3124. # Same precedence as _FeishuBotIdentity.matches (open_id > user_id > name); a non-empty
  3125. # bot_name here only matches an exact stripped name, while an empty bot_name never matches.
  3126. bot = self._bot_identity()
  3127. for mention in mentions:
  3128. mention_id = getattr(mention, "id", None)
  3129. if bot.matches(
  3130. open_id=(getattr(mention_id, "open_id", None) or "").strip(),
  3131. user_id=(getattr(mention_id, "user_id", None) or "").strip(),
  3132. name=(getattr(mention, "name", None) or "").strip(),
  3133. ):
  3134. return True
  3135. return False
  3136. def _post_mentions_bot(self, mentions: list[FeishuMentionRef]) -> bool:
  3137. return any(m.is_self for m in mentions)
  3138. def _bot_identity(self) -> _FeishuBotIdentity:
  3139. return _FeishuBotIdentity(open_id=self._bot_open_id, user_id=self._bot_user_id, name=self._bot_name)
  3140. async def _hydrate_bot_identity(self) -> None:
  3141. """Best-effort bot identity discovery for mention gating and self-event filtering.
  3142. /bot/v3/info (tenant token, no extra scopes) always wins over env values so stale
  3143. FEISHU_BOT_* from app migrations can't break gating; the application-info endpoint is
  3144. a name-only fallback. On failure env-provided values are kept.
  3145. """
  3146. if not self._client:
  3147. return
  3148. try:
  3149. content = await self._tenant_get_raw("/open-apis/bot/v3/info")
  3150. if content:
  3151. payload = json.loads(content)
  3152. parsed = _parse_bot_response(payload) or {}
  3153. open_id = (parsed.get("bot_open_id") or "").strip()
  3154. bot_name = (parsed.get("bot_name") or "").strip()
  3155. if open_id:
  3156. if self._bot_open_id and self._bot_open_id != open_id:
  3157. logger.warning(
  3158. "[Feishu] FEISHU_BOT_OPEN_ID is stale; using /bot/v3/info open_id for group @mention gating."
  3159. )
  3160. self._bot_open_id = open_id
  3161. if bot_name:
  3162. if self._bot_name and self._bot_name != bot_name:
  3163. logger.info(
  3164. "[Feishu] FEISHU_BOT_NAME differs from /bot/v3/info; using hydrated bot name for group @mention gating."
  3165. )
  3166. self._bot_name = bot_name
  3167. except Exception:
  3168. logger.debug("[Feishu] /bot/v3/info probe failed during hydration", exc_info=True)
  3169. if self._bot_name:
  3170. return
  3171. # Name-only fallback; needs admin:app.info:readonly or application:application:self_manage.
  3172. try:
  3173. request = self._build_get_application_request(app_id=self._app_id, lang="en_us")
  3174. response = await self._run_blocking(self._client.application.v6.application.get, request)
  3175. if not response or not response.success():
  3176. code = getattr(response, "code", None)
  3177. if code == 99991672:
  3178. logger.warning(
  3179. "[Feishu] Unable to hydrate bot name from application info. "
  3180. "Grant admin:app.info:readonly or application:application:self_manage "
  3181. "so group @mention gating can resolve the bot name precisely."
  3182. )
  3183. return
  3184. app = getattr(getattr(response, "data", None), "app", None)
  3185. app_name = (getattr(app, "app_name", None) or "").strip()
  3186. if app_name and not self._bot_name:
  3187. self._bot_name = app_name
  3188. except Exception:
  3189. logger.debug("[Feishu] Failed to hydrate bot name from application info", exc_info=True)
  3190. # --- Deduplication — seen message ID cache (persistent) ---
  3191. def _load_seen_message_ids(self) -> None:
  3192. try:
  3193. payload = json.loads(self._dedup_state_path.read_text(encoding="utf-8-sig"))
  3194. except FileNotFoundError:
  3195. return
  3196. except (OSError, json.JSONDecodeError):
  3197. logger.warning("[Feishu] Failed to load persisted dedup state from %s", self._dedup_state_path, exc_info=True)
  3198. return
  3199. seen_data = payload.get("message_ids", {}) if isinstance(payload, dict) else {}
  3200. now = time.time()
  3201. ttl = _FEISHU_DEDUP_TTL_SECONDS
  3202. if isinstance(seen_data, list): # legacy format: plain list of IDs, no timestamps
  3203. entries: dict[str, float] = {str(item).strip(): 0.0 for item in seen_data if str(item).strip()}
  3204. elif isinstance(seen_data, dict):
  3205. entries = {}
  3206. for key, value in seen_data.items():
  3207. if isinstance(key, str) and key.strip() and isinstance(value, (int, float, str)):
  3208. try:
  3209. entries[key] = float(value)
  3210. except ValueError:
  3211. pass
  3212. else:
  3213. return
  3214. # Drop TTL-expired entries; ts=0.0 (legacy) is immortal for one migration cycle.
  3215. valid: dict[str, float] = {m: ts for m, ts in entries.items() if ts == 0.0 or ttl <= 0 or now - ts < ttl}
  3216. # Size cap keeps the most recently seen IDs.
  3217. sorted_ids = sorted(valid, key=lambda k: valid[k], reverse=True)[:self._dedup_cache_size]
  3218. self._seen_message_order = list(reversed(sorted_ids))
  3219. self._seen_message_ids = {k: valid[k] for k in sorted_ids}
  3220. def _persist_seen_message_ids(self) -> None:
  3221. try:
  3222. from hermes_constants import mkdir_under_hermes_home
  3223. mkdir_under_hermes_home(self._dedup_state_path.parent)
  3224. with self._dedup_lock:
  3225. recent = self._seen_message_order[-self._dedup_cache_size:]
  3226. # Save as {msg_id: timestamp} so TTL filtering works across restarts.
  3227. payload = {"message_ids": {k: self._seen_message_ids[k] for k in recent if k in self._seen_message_ids}}
  3228. atomic_json_write(self._dedup_state_path, payload, indent=None)
  3229. except OSError:
  3230. logger.warning("[Feishu] Failed to persist dedup state to %s", self._dedup_state_path, exc_info=True)
  3231. async def _is_duplicate(self, message_id: str) -> bool:
  3232. now, ttl = time.time(), _FEISHU_DEDUP_TTL_SECONDS
  3233. with self._dedup_lock:
  3234. seen_at = self._seen_message_ids.get(message_id)
  3235. if seen_at is not None and (ttl <= 0 or now - seen_at < ttl):
  3236. return True
  3237. self._seen_message_ids[message_id] = now # wall-clock so TTL survives restarts
  3238. self._seen_message_order.append(message_id)
  3239. while len(self._seen_message_order) > self._dedup_cache_size:
  3240. self._seen_message_ids.pop(self._seen_message_order.pop(0), None)
  3241. # atomic_json_write() fsyncs; this runs on the event loop for every inbound message, so
  3242. # offload the flush onto the adapter-owned pool: the loop's default executor may already
  3243. # be torn down by a dead background loop, which used to wedge every inbound message in
  3244. # the dedup gate (#111020). The lock keeps flushes in mutation order (the snapshot
  3245. # inside the worker is taken under _dedup_lock, but the write itself is not).
  3246. async with self._dedup_persist_lock_or_create():
  3247. await self._run_blocking(self._persist_seen_message_ids)
  3248. return False
  3249. def _dedup_persist_lock_or_create(self) -> asyncio.Lock:
  3250. # Tests build bare adapters via object.__new__ and install dedup state
  3251. # by hand; create the lock lazily so those fixtures keep working.
  3252. lock = getattr(self, "_dedup_persist_lock", None)
  3253. if lock is None:
  3254. lock = self._dedup_persist_lock = asyncio.Lock()
  3255. return lock
  3256. # --- Outbound payload construction and send pipeline ---
  3257. def _build_outbound_payload(self, content: str, *, prefer_post: bool = False) -> tuple[str, str]:
  3258. # Feishu clients render markdown tables inside ``post`` ``md`` elements natively, so tables
  3259. # take the common markdown path (no text downgrade). ``prefer_post`` lets ``send`` keep every
  3260. # chunk of a split markdown reply as ``post`` even when a chunk alone looks like prose.
  3261. # The previous table-downgrade branch forced any table-containing message to ``text``, which left
  3262. # Feishu readers seeing the raw pipe-and-dash source instead of a rendered table. ``prefer_post``
  3263. # lets ``send`` treat the chunk as part of a larger markdown document: when a long markdown reply is
  3264. # split at MAX_MESSAGE_LENGTH, the per-chunk regex would otherwise mis-classify a plain-prose chunk
  3265. # as ``text``. See #26841.
  3266. if prefer_post or _MARKDOWN_HINT_RE.search(content):
  3267. return "post", _build_markdown_post_payload(content)
  3268. return "text", json.dumps({"text": content}, ensure_ascii=False)
  3269. @staticmethod
  3270. def _get_audio_duration_ms(file_path: str) -> int:
  3271. """OGG/Opus duration in ms (pure Python): last granule position / 48000 Hz; 0 on non-OGG or error."""
  3272. import struct
  3273. try:
  3274. with open(file_path, "rb") as f:
  3275. data = f.read()
  3276. pos = last_granule = 0
  3277. while pos < len(data) - 27:
  3278. pos = data.find(b"OggS", pos)
  3279. if pos == -1 or pos + 27 > len(data):
  3280. break
  3281. granule = struct.unpack_from("<q", data, pos + 6)[0]
  3282. num_segments = data[pos + 26]
  3283. last_granule = granule if granule > 0 else last_granule
  3284. if pos + 27 + num_segments > len(data):
  3285. break
  3286. pos += num_segments + sum(data[pos + 27 : pos + 27 + num_segments])
  3287. return int(last_granule / 48000 * 1000) if last_granule > 0 else 0
  3288. except Exception:
  3289. return 0
  3290. async def _send_uploaded_file_message(
  3291. self, *, chat_id: str, file_path: str, reply_to: Optional[str], metadata: Optional[dict[str, Any]],
  3292. caption: Optional[str] = None, file_name: Optional[str] = None, outbound_message_type: str = "file",
  3293. ) -> SendResult:
  3294. if not self._client:
  3295. return SendResult(success=False, error="Not connected")
  3296. if not os.path.exists(file_path):
  3297. return SendResult(success=False, error=f"File not found: {file_path}")
  3298. display_name = file_name or os.path.basename(file_path)
  3299. upload_file_type, resolved_message_type = self._resolve_outbound_file_routing(
  3300. file_path=display_name, requested_message_type=outbound_message_type,
  3301. )
  3302. try:
  3303. duration_ms = self._get_audio_duration_ms(file_path) if upload_file_type == "opus" else 0
  3304. with open(file_path, "rb") as file_obj: # noqa: ASYNC230 -- file handle is streamed to the upload; a local open() is non-blocking in practice
  3305. body = self._build_file_upload_body(
  3306. file_type=upload_file_type, file_name=display_name, file=file_obj, duration=duration_ms,
  3307. )
  3308. request = self._build_file_upload_request(body)
  3309. upload_response = await self._run_blocking(self._client.im.v1.file.create, request)
  3310. file_key = self._extract_response_field(upload_response, "file_key")
  3311. if not file_key:
  3312. return self._response_error_result(
  3313. upload_response, default_message="file upload failed",
  3314. override_error="Feishu file upload missing file_key",
  3315. )
  3316. key_payload = {"file_key": file_key}
  3317. message_response = await self._send_uploaded_key(
  3318. chat_id=chat_id, reply_to=reply_to, metadata=metadata, caption=caption,
  3319. key_msg_type=resolved_message_type, key_payload=key_payload,
  3320. media_tag={"tag": "media", "file_key": file_key, "file_name": display_name},
  3321. )
  3322. # Audio may fail with 99992402 under thread_id routing: retry as a reply to the
  3323. # thread's last message, then fall back to a plain chat_id send.
  3324. if (not caption
  3325. and not self._response_succeeded(message_response)
  3326. and getattr(message_response, "code", None) == 99992402
  3327. and resolved_message_type == "audio"
  3328. and (metadata or {}).get("thread_id")):
  3329. payload = json.dumps(key_payload, ensure_ascii=False)
  3330. thread_msg_id = (metadata or {}).get("reply_to_message_id")
  3331. if not thread_msg_id:
  3332. thread_msg_id = await self._fetch_last_message_in_thread((metadata or {}).get("thread_id"))
  3333. if thread_msg_id:
  3334. logger.info("[Feishu] Audio: retrying via reply API in thread")
  3335. message_response = await self._feishu_send_with_retry(
  3336. chat_id=chat_id, msg_type="audio", payload=payload, reply_to=thread_msg_id, metadata=metadata,
  3337. )
  3338. if not self._response_succeeded(message_response):
  3339. logger.warning("[Feishu] Audio send failed in thread, retrying with chat_id")
  3340. message_response = await self._feishu_send_with_retry(
  3341. chat_id=chat_id, msg_type="audio", payload=payload, reply_to=None, metadata=None,
  3342. )
  3343. return self._finalize_send_result(message_response, "file send failed")
  3344. except Exception as exc:
  3345. logger.error("[Feishu] Failed to send file %s: %s", file_path, exc, exc_info=True)
  3346. return SendResult(success=False, error=str(exc))
  3347. async def _send_uploaded_key(
  3348. self, *, chat_id: str, reply_to: Optional[str], metadata: Optional[dict[str, Any]], caption: Optional[str],
  3349. key_msg_type: str, key_payload: dict[str, str], media_tag: dict[str, str],
  3350. ) -> Any:
  3351. """Send an uploaded image/file key: as a captioned ``post`` or as a bare key message."""
  3352. if caption:
  3353. msg_type = "post"
  3354. payload = self._build_media_post_payload(caption=caption, media_tag=media_tag)
  3355. else:
  3356. msg_type = key_msg_type
  3357. payload = json.dumps(key_payload, ensure_ascii=False)
  3358. return await self._feishu_send_with_retry(
  3359. chat_id=chat_id, msg_type=msg_type, payload=payload, reply_to=reply_to, metadata=metadata,
  3360. )
  3361. async def _fetch_last_message_in_thread(self, thread_id: str) -> Optional[str]:
  3362. """Fetch the last message_id in a thread for reply-based routing."""
  3363. if not self._client or not thread_id:
  3364. return None
  3365. try:
  3366. from lark_oapi.api.im.v1 import ListMessageRequest
  3367. request = ListMessageRequest.builder().container_id_type("thread").container_id(thread_id).page_size(1).build()
  3368. response = await self._run_blocking(self._client.im.v1.message.list, request)
  3369. if self._response_succeeded(response):
  3370. items = getattr(getattr(response, "data", None), "items", None)
  3371. if items and len(items) > 0:
  3372. return getattr(items[0], "message_id", None)
  3373. except Exception as exc:
  3374. logger.debug("[Feishu] Failed to fetch last message in thread %s: %s", thread_id, exc)
  3375. return None
  3376. async def _send_raw_message(
  3377. self, *, chat_id: str, msg_type: str, payload: str, reply_to: Optional[str], metadata: Optional[dict[str, Any]],
  3378. ) -> Any:
  3379. thread_id = (metadata or {}).get("thread_id")
  3380. effective_reply_to = reply_to or ((metadata or {}).get("reply_to_message_id") if thread_id else None)
  3381. if effective_reply_to:
  3382. body = self._build_reply_message_body(
  3383. content=payload, msg_type=msg_type, reply_in_thread=bool(thread_id), uuid_value=str(uuid.uuid4()),
  3384. )
  3385. request = self._build_reply_message_request(effective_reply_to, body)
  3386. return await self._run_blocking(self._client.im.v1.message.reply, request)
  3387. if thread_id:
  3388. # reply→create fallback inside a topic: thread_id as receive_id keeps it in the topic.
  3389. receive_id, receive_id_type = thread_id, "thread_id"
  3390. elif chat_id.startswith("feishu_user_id:"):
  3391. receive_id, receive_id_type = chat_id.split(":", 1)[1], "user_id"
  3392. else:
  3393. receive_id, receive_id_type = chat_id, "open_id" if chat_id.startswith("ou_") else "chat_id"
  3394. body = self._build_create_message_body(
  3395. receive_id=receive_id, msg_type=msg_type, content=payload, uuid_value=str(uuid.uuid4()),
  3396. )
  3397. request = self._build_create_message_request(receive_id_type, body)
  3398. return await self._run_blocking(self._client.im.v1.message.create, request)
  3399. @staticmethod
  3400. def _response_succeeded(response: Any) -> bool:
  3401. return bool(response and getattr(response, "success", lambda: False)())
  3402. @staticmethod
  3403. def _extract_response_field(response: Any, field_name: str) -> Any:
  3404. data = getattr(response, "data", None) if FeishuAdapter._response_succeeded(response) else None
  3405. return getattr(data, field_name, None) if data else None
  3406. def _response_error_result(
  3407. self, response: Any, *, default_message: str, override_error: Optional[str] = None,
  3408. ) -> SendResult:
  3409. if override_error:
  3410. return SendResult(success=False, error=override_error, raw_response=response)
  3411. code = getattr(response, "code", "unknown")
  3412. msg = getattr(response, "msg", default_message)
  3413. return SendResult(success=False, error=f"[{code}] {msg}", raw_response=response)
  3414. def _finalize_send_result(self, response: Any, default_message: str) -> SendResult:
  3415. if not self._response_succeeded(response):
  3416. return self._response_error_result(response, default_message=default_message)
  3417. return SendResult(
  3418. success=True, message_id=self._extract_response_field(response, "message_id"),
  3419. raw_response=response,
  3420. )
  3421. # --- Connection internals — websocket / webhook setup ---
  3422. async def _connect_with_retry(self) -> None:
  3423. for attempt in range(_FEISHU_CONNECT_ATTEMPTS):
  3424. try:
  3425. if self._connection_mode == "websocket":
  3426. await self._connect_websocket()
  3427. else:
  3428. await self._connect_webhook()
  3429. return
  3430. except Exception as exc:
  3431. self._running = False
  3432. self._disable_websocket_auto_reconnect()
  3433. self._ws_future = None
  3434. await self._stop_webhook_server()
  3435. if attempt >= _FEISHU_CONNECT_ATTEMPTS - 1:
  3436. raise
  3437. wait_seconds = 2 ** attempt
  3438. logger.warning(
  3439. "[Feishu] Connect attempt %d/%d failed; retrying in %ds: %s",
  3440. attempt + 1, _FEISHU_CONNECT_ATTEMPTS, wait_seconds, exc,
  3441. )
  3442. await asyncio.sleep(wait_seconds)
  3443. async def _supervise_websocket_thread(self) -> None:
  3444. """Restart the WS client thread if it dies while the adapter is up.
  3445. ``lark_oapi.start()`` only returns on fatal errors; without this watcher a dead thread
  3446. left the profile silently deaf until a gateway restart. Rebuild with capped backoff.
  3447. See #73779.
  3448. """
  3449. backoff = initial_backoff = float(self._ws_restart_backoff)
  3450. last_dead: Optional[asyncio.Future] = None
  3451. while self._running:
  3452. ws_future = self._ws_future
  3453. if ws_future is None:
  3454. return
  3455. try:
  3456. await asyncio.shield(ws_future)
  3457. except asyncio.CancelledError:
  3458. raise
  3459. except Exception:
  3460. pass
  3461. # Deliberate disconnects nil ``_ws_client``/``_running`` first; only restart a live link.
  3462. if not self._running or self._ws_client is None:
  3463. return
  3464. if ws_future is not last_dead:
  3465. logger.error("[Feishu] WebSocket client thread exited unexpectedly; restarting in %.0fs", backoff)
  3466. last_dead = ws_future
  3467. # Still running, link unproven: ``connected`` stays wrong until ``_ws_link_up`` re-stamps it.
  3468. self._write_runtime_status_safe(
  3469. "ws_link_lost", platform_state="retrying", error_code=None,
  3470. error_message="Feishu websocket link lost; rebuilding",
  3471. )
  3472. await asyncio.sleep(backoff)
  3473. if not self._running:
  3474. return
  3475. try:
  3476. await self._connect_websocket()
  3477. backoff = initial_backoff
  3478. except Exception as exc:
  3479. logger.warning("[Feishu] WebSocket restart failed (retrying): %s", exc)
  3480. backoff = min(backoff * 2, 60.0)
  3481. def _ws_link_up(self, ws_client: Any) -> None:
  3482. """WS thread reports its link is up (SDK receive loop scheduled); re-stamp ``connected`` after a rebuild."""
  3483. if self._running and self._ws_client is ws_client:
  3484. self._mark_connected()
  3485. def _ws_link_retrying(self, ws_client: Any) -> None:
  3486. """WS thread reports the SDK's own reconnect ladder started; ``_ws_link_up`` re-stamps ``connected``."""
  3487. if self._running and self._ws_client is ws_client:
  3488. self._write_runtime_status_safe(
  3489. "ws_link_lost", platform_state="retrying", error_code=None,
  3490. error_message="Feishu websocket link lost; reconnecting",
  3491. )
  3492. async def _connect_websocket(self) -> None:
  3493. if not FEISHU_WEBSOCKET_AVAILABLE:
  3494. raise RuntimeError("websockets not installed; websocket mode unavailable")
  3495. domain = self._prepare_client()
  3496. loop = self._loop
  3497. if loop is None or loop.is_closed():
  3498. raise RuntimeError("adapter loop is not ready")
  3499. await self._hydrate_bot_identity()
  3500. self._ws_client = FeishuWSClient(
  3501. app_id=self._app_id,
  3502. app_secret=self._app_secret,
  3503. log_level=lark.LogLevel.INFO,
  3504. event_handler=self._event_handler,
  3505. domain=domain,
  3506. # Without the "channel" UA tag Feishu won't push group @mention events over WS.
  3507. extra_ua_tags=["channel"],
  3508. )
  3509. # The lark SDK owns this thread and fires every event/card callback on it; those hop back
  3510. # to the adapter loop via run_coroutine_threadsafe, which copies the CALLER's context — so
  3511. # whatever scope the WS thread carries is what pre-handler work (inbound media caching,
  3512. # .update_response marker, reactions env, drive comments) runs under. A bare executor
  3513. # thread has an empty context = launch profile. connect() runs inside the profile scope
  3514. # under multiplex (and the supervisor task inherits it), so snapshot it here.
  3515. self._ws_future = loop.run_in_executor(
  3516. self._get_sdk_executor(), contextvars.copy_context().run, _run_official_feishu_ws_client, self._ws_client, self)
  3517. async def _connect_webhook(self) -> None:
  3518. if not FEISHU_WEBHOOK_AVAILABLE:
  3519. raise RuntimeError("aiohttp not installed; webhook mode unavailable")
  3520. self._prepare_client()
  3521. await self._hydrate_bot_identity()
  3522. # client_max_size backstops the bounded reader in _handle_webhook_request on every read path.
  3523. # See #58536, #58902, #59180.
  3524. app = web.Application(client_max_size=_FEISHU_WEBHOOK_MAX_BODY_BYTES)
  3525. app.router.add_post(self._webhook_path, self._handle_webhook_request)
  3526. # Shared-listener mode (multiplex secondary): no bind; served at /p/<profile>/<webhook_path>.
  3527. from gateway.platforms.shared_ingress import bind_listener
  3528. self._webhook_runner = await bind_listener(self, app, self._webhook_host, self._webhook_port, self._webhook_path)
  3529. def _prepare_client(self) -> Any:
  3530. """Build the lark client + event dispatcher for this adapter's domain; returns the SDK domain."""
  3531. domain = _sdk_domain(self._domain_name)
  3532. self._client = self._build_lark_client(domain)
  3533. self._event_handler = self._build_event_handler()
  3534. if self._event_handler is None:
  3535. raise RuntimeError("failed to build Feishu event handler")
  3536. return domain
  3537. def _build_lark_client(self, domain: Any) -> Any:
  3538. return _build_lark_client(self._app_id, self._app_secret, domain)
  3539. async def _feishu_send_with_retry(
  3540. self, *, chat_id: str, msg_type: str, payload: str, reply_to: Optional[str], metadata: Optional[dict[str, Any]],
  3541. ) -> Any:
  3542. last_error: Optional[Exception] = None
  3543. active_reply_to = reply_to
  3544. async def _raw(reply_target: Optional[str]) -> Any:
  3545. return await self._send_raw_message(
  3546. chat_id=chat_id, msg_type=msg_type, payload=payload, reply_to=reply_target, metadata=metadata,
  3547. )
  3548. for attempt in range(_FEISHU_SEND_ATTEMPTS):
  3549. try:
  3550. response = await _raw(active_reply_to)
  3551. # Reply target withdrawn/missing → post a new message to the chat instead.
  3552. if active_reply_to and not self._response_succeeded(response):
  3553. code = getattr(response, "code", None)
  3554. if code in _FEISHU_REPLY_FALLBACK_CODES:
  3555. if (metadata or {}).get("thread_id"):
  3556. logger.warning(
  3557. "[Feishu] Reply to %s failed in thread %s (code %s — message withdrawn/missing); "
  3558. "skipping top-level fallback to avoid creating a new topic",
  3559. active_reply_to, (metadata or {}).get("thread_id"), code,
  3560. )
  3561. return response
  3562. logger.warning(
  3563. "[Feishu] Reply to %s failed (code %s — message withdrawn/missing); "
  3564. "falling back to new message in chat %s",
  3565. active_reply_to, code, chat_id,
  3566. )
  3567. active_reply_to = None
  3568. response = await _raw(None)
  3569. return response
  3570. except Exception as exc:
  3571. last_error = exc
  3572. if msg_type == "post" and _POST_CONTENT_INVALID_RE.search(str(exc)):
  3573. raise
  3574. if attempt >= _FEISHU_SEND_ATTEMPTS - 1:
  3575. raise
  3576. wait_seconds = 2 ** attempt
  3577. logger.warning(
  3578. "[Feishu] Send attempt %d/%d failed for chat %s; retrying in %ds: %s",
  3579. attempt + 1, _FEISHU_SEND_ATTEMPTS, chat_id, wait_seconds, exc,
  3580. )
  3581. await asyncio.sleep(wait_seconds)
  3582. raise last_error or RuntimeError("Feishu send failed")
  3583. async def _release_app_lock(self) -> None:
  3584. if not self._app_lock_identity:
  3585. return
  3586. try:
  3587. release_scoped_lock(_FEISHU_APP_LOCK_SCOPE, self._app_lock_identity)
  3588. except Exception as exc:
  3589. logger.warning("[Feishu] Failed to release app lock: %s", exc, exc_info=True)
  3590. finally:
  3591. self._app_lock_identity = None
  3592. # --- Lark API request builders (SimpleNamespace fallback when the SDK is unbound) ---
  3593. @staticmethod
  3594. def _build_get_chat_request(chat_id: str) -> Any:
  3595. return _sdk_build(GetChatRequest, chat_id=chat_id)
  3596. @staticmethod
  3597. def _build_get_message_request(message_id: str) -> Any:
  3598. return _sdk_build(GetMessageRequest, message_id=message_id)
  3599. @staticmethod
  3600. def _build_message_resource_request(*, message_id: str, file_key: str, resource_type: str) -> Any:
  3601. return _sdk_build(GetMessageResourceRequest, message_id=message_id, file_key=file_key, type=resource_type)
  3602. @staticmethod
  3603. def _build_get_application_request(*, app_id: str, lang: str) -> Any:
  3604. return _sdk_build(GetApplicationRequest, app_id=app_id, lang=lang)
  3605. @staticmethod
  3606. def _build_reply_message_body(*, content: str, msg_type: str, reply_in_thread: bool, uuid_value: str) -> Any:
  3607. return _sdk_build(
  3608. ReplyMessageRequestBody,
  3609. content=content, msg_type=msg_type, reply_in_thread=reply_in_thread, uuid=uuid_value,
  3610. )
  3611. @staticmethod
  3612. def _build_reply_message_request(message_id: str, request_body: Any) -> Any:
  3613. return _sdk_build(ReplyMessageRequest, message_id=message_id, request_body=request_body)
  3614. @staticmethod
  3615. def _build_update_message_body(*, msg_type: str, content: str) -> Any:
  3616. return _sdk_build(UpdateMessageRequestBody, msg_type=msg_type, content=content)
  3617. @staticmethod
  3618. def _build_update_message_request(message_id: str, request_body: Any) -> Any:
  3619. return _sdk_build(UpdateMessageRequest, message_id=message_id, request_body=request_body)
  3620. @staticmethod
  3621. def _build_delete_message_request(message_id: str) -> Any:
  3622. return _sdk_build(DeleteMessageRequest, message_id=message_id)
  3623. @staticmethod
  3624. def _build_create_message_body(*, receive_id: str, msg_type: str, content: str, uuid_value: str) -> Any:
  3625. return _sdk_build(
  3626. CreateMessageRequestBody, receive_id=receive_id, msg_type=msg_type, content=content, uuid=uuid_value,
  3627. )
  3628. @staticmethod
  3629. def _build_create_message_request(receive_id_type: str, request_body: Any) -> Any:
  3630. return _sdk_build(CreateMessageRequest, receive_id_type=receive_id_type, request_body=request_body)
  3631. @staticmethod
  3632. def _build_image_upload_body(*, image_type: str, image: Any) -> Any:
  3633. return _sdk_build(CreateImageRequestBody, image_type=image_type, image=image)
  3634. @staticmethod
  3635. def _build_image_upload_request(request_body: Any) -> Any:
  3636. return _sdk_build(CreateImageRequest, request_body=request_body)
  3637. @staticmethod
  3638. def _build_file_upload_body(*, file_type: str, file_name: str, file: Any, duration: int = 0) -> Any:
  3639. if CreateFileRequestBody is None:
  3640. return SimpleNamespace(file_type=file_type, file_name=file_name, file=file, duration=duration)
  3641. fields: dict[str, Any] = {"file_type": file_type, "file_name": file_name, "file": file}
  3642. if duration > 0:
  3643. fields["duration"] = duration
  3644. return _sdk_build(CreateFileRequestBody, **fields)
  3645. @staticmethod
  3646. def _build_file_upload_request(request_body: Any) -> Any:
  3647. return _sdk_build(CreateFileRequest, request_body=request_body)
  3648. def _build_media_post_payload(self, *, caption: str, media_tag: dict[str, str]) -> str:
  3649. payload = json.loads(_build_markdown_post_payload(caption))
  3650. content = payload.setdefault("zh_cn", {}).setdefault("content", [])
  3651. content.append([media_tag])
  3652. return json.dumps(payload, ensure_ascii=False)
  3653. @staticmethod
  3654. def _resolve_outbound_file_routing(*, file_path: str, requested_message_type: str) -> tuple[str, str]:
  3655. # Opus only becomes an ``audio`` message (Lark's in-app voice recording) when the caller asked
  3656. # for one (send_voice with voice intent); a document/plain-audio send of an .ogg stays a file.
  3657. ext = Path(file_path).suffix.lower()
  3658. if ext in _FEISHU_OPUS_UPLOAD_EXTENSIONS and requested_message_type == "audio":
  3659. return "opus", "audio"
  3660. if ext in _FEISHU_MEDIA_UPLOAD_EXTENSIONS:
  3661. return "mp4", "media"
  3662. if ext in _FEISHU_DOC_UPLOAD_TYPES:
  3663. return _FEISHU_DOC_UPLOAD_TYPES[ext], "file"
  3664. return _FEISHU_FILE_UPLOAD_TYPE, "file"
  3665. # --- QR scan-to-create onboarding (device-code flow; Feishu creates a configured bot app) ---
  3666. def _accounts_base_url(domain: str) -> str:
  3667. return _ONBOARD_ACCOUNTS_URLS.get(domain, _ONBOARD_ACCOUNTS_URLS["feishu"])
  3668. def _onboard_open_base_url(domain: str) -> str:
  3669. return _ONBOARD_OPEN_URLS.get(domain, _ONBOARD_OPEN_URLS["feishu"])
  3670. def _post_registration(base_url: str, body: dict[str, str]) -> dict:
  3671. """POST form data to the registration endpoint; parse JSON even on 4xx (poll's pending is a 400)."""
  3672. req = Request(
  3673. f"{base_url}{_REGISTRATION_PATH}", data=urlencode(body).encode("utf-8"),
  3674. headers={"Content-Type": "application/x-www-form-urlencoded"},
  3675. )
  3676. try:
  3677. with urlopen(req, timeout=_ONBOARD_REQUEST_TIMEOUT_S) as resp:
  3678. return json.loads(resp.read().decode("utf-8"))
  3679. except HTTPError as exc:
  3680. body_bytes = exc.read()
  3681. if body_bytes:
  3682. try:
  3683. return json.loads(body_bytes.decode("utf-8"))
  3684. except (ValueError, json.JSONDecodeError):
  3685. raise exc from None
  3686. raise
  3687. def _init_registration(domain: str = "feishu") -> None:
  3688. """Raise RuntimeError unless the registration environment supports client_secret auth."""
  3689. res = _post_registration(_accounts_base_url(domain), {"action": "init"})
  3690. methods = res.get("supported_auth_methods") or []
  3691. if "client_secret" not in methods:
  3692. raise RuntimeError(
  3693. f"Feishu / Lark registration environment does not support client_secret auth. "
  3694. f"Supported: {methods}"
  3695. )
  3696. def _begin_registration(domain: str = "feishu") -> dict:
  3697. """Start the device-code flow. Returns device_code, qr_url, user_code, interval, expire_in."""
  3698. res = _post_registration(_accounts_base_url(domain), {
  3699. "action": "begin", "archetype": "PersonalAgent", "auth_method": "client_secret", "request_user_info": "open_id",
  3700. })
  3701. device_code = res.get("device_code")
  3702. if not device_code:
  3703. raise RuntimeError("Feishu / Lark registration did not return a device_code")
  3704. qr_url = res.get("verification_uri_complete", "")
  3705. qr_url += ("&" if "?" in qr_url else "?") + "from=hermes&tp=hermes"
  3706. return {
  3707. "device_code": device_code, "qr_url": qr_url, "user_code": res.get("user_code", ""),
  3708. "interval": res.get("interval") or 5, "expire_in": res.get("expire_in") or 600,
  3709. }
  3710. def _poll_registration(*, device_code: str, interval: int, expire_in: int, domain: str = "feishu") -> Optional[dict]:
  3711. """Poll until scan (→ {app_id, app_secret, domain, open_id}), or None on denial/timeout."""
  3712. deadline = time.monotonic() + expire_in
  3713. current_domain = domain
  3714. domain_switched = False
  3715. poll_count = 0
  3716. while time.monotonic() < deadline:
  3717. try:
  3718. body = {"action": "poll", "device_code": device_code, "tp": "ob_app"}
  3719. res = _post_registration(_accounts_base_url(current_domain), body)
  3720. except (URLError, OSError, json.JSONDecodeError):
  3721. time.sleep(interval)
  3722. continue
  3723. poll_count += 1
  3724. if poll_count == 1:
  3725. print(" Fetching configuration results...", end="", flush=True)
  3726. elif poll_count % 6 == 0:
  3727. print(".", end="", flush=True)
  3728. # Domain auto-detection; fall through — this same response may carry credentials.
  3729. user_info = res.get("user_info") or {}
  3730. if user_info.get("tenant_brand") == "lark" and not domain_switched:
  3731. current_domain = "lark"
  3732. domain_switched = True
  3733. if res.get("client_id") and res.get("client_secret"):
  3734. if poll_count > 0:
  3735. print() # newline after "Fetching configuration results..." dots
  3736. return {
  3737. "app_id": res["client_id"], "app_secret": res["client_secret"], "domain": current_domain,
  3738. "open_id": user_info.get("open_id"),
  3739. }
  3740. error = res.get("error", "")
  3741. if error in {"access_denied", "expired_token"}:
  3742. if poll_count > 0:
  3743. print()
  3744. logger.warning("[Feishu onboard] Registration %s", error)
  3745. return None
  3746. time.sleep(interval) # authorization_pending or unknown — keep polling
  3747. if poll_count > 0:
  3748. print()
  3749. logger.warning("[Feishu onboard] Poll timed out after %ds", expire_in)
  3750. return None
  3751. try:
  3752. import qrcode as _qrcode_mod
  3753. except (ImportError, TypeError):
  3754. _qrcode_mod = None # type: ignore[assignment]
  3755. def _render_qr(url: str) -> bool:
  3756. """Try to render a QR code in the terminal. Returns True if successful."""
  3757. if _qrcode_mod is None:
  3758. return False
  3759. try:
  3760. qr = _qrcode_mod.QRCode()
  3761. qr.add_data(url)
  3762. qr.make(fit=True)
  3763. qr.print_ascii(invert=True)
  3764. return True
  3765. except Exception:
  3766. return False
  3767. def probe_bot(app_id: str, app_secret: str, domain: str) -> Optional[dict]:
  3768. """Probe /open-apis/bot/v3/info → {"bot_name", "bot_open_id"} (app-scoped open_id, NOT app_id) or None.
  3769. Onboarding runs before connect(), so load the SDK here instead of always falling back to HTTP.
  3770. """
  3771. if _load_lark_oapi():
  3772. return _probe_bot_sdk(app_id, app_secret, domain)
  3773. return _probe_bot_http(app_id, app_secret, domain)
  3774. def _build_onboard_client(app_id: str, app_secret: str, domain: str) -> Any:
  3775. """Build a lark Client for the given credentials and domain name ("feishu"/"lark")."""
  3776. return _build_lark_client(app_id, app_secret, _sdk_domain(domain))
  3777. def _parse_bot_response(data: dict) -> Optional[dict]:
  3778. # /bot/v3/info returns bot.app_name; legacy paths used bot_name — accept both.
  3779. if data.get("code") != 0:
  3780. return None
  3781. bot = data.get("bot") or data.get("data", {}).get("bot") or {}
  3782. return {
  3783. "bot_name": bot.get("app_name") or bot.get("bot_name"),
  3784. "bot_open_id": bot.get("open_id"),
  3785. }
  3786. def _probe_bot_sdk(app_id: str, app_secret: str, domain: str) -> Optional[dict]:
  3787. """Probe bot info using lark_oapi SDK."""
  3788. try:
  3789. resp = _build_onboard_client(app_id, app_secret, domain).request(_tenant_get_request("/open-apis/bot/v3/info"))
  3790. content = getattr(getattr(resp, "raw", None), "content", None)
  3791. return None if content is None else _parse_bot_response(json.loads(content))
  3792. except Exception as exc:
  3793. logger.debug("[Feishu onboard] SDK probe failed: %s", exc)
  3794. return None
  3795. def _probe_bot_http(app_id: str, app_secret: str, domain: str) -> Optional[dict]:
  3796. """Fallback probe using raw HTTP (when lark_oapi is not installed)."""
  3797. base_url = _onboard_open_base_url(domain)
  3798. def _get_json(path: str, *, data: Optional[bytes] = None, extra_headers: Optional[dict[str, str]] = None) -> dict:
  3799. headers = {**(extra_headers or {}), "Content-Type": "application/json"}
  3800. with urlopen(Request(f"{base_url}{path}", data=data, headers=headers), timeout=_ONBOARD_REQUEST_TIMEOUT_S) as resp:
  3801. return json.loads(resp.read().decode("utf-8"))
  3802. try:
  3803. token_res = _get_json(
  3804. "/open-apis/auth/v3/tenant_access_token/internal",
  3805. data=json.dumps({"app_id": app_id, "app_secret": app_secret}).encode("utf-8"),
  3806. )
  3807. access_token = token_res.get("tenant_access_token")
  3808. if not access_token:
  3809. return None
  3810. bot_res = _get_json("/open-apis/bot/v3/info", extra_headers={"Authorization": f"Bearer {access_token}"})
  3811. return _parse_bot_response(bot_res)
  3812. except (URLError, OSError, KeyError, json.JSONDecodeError) as exc:
  3813. logger.debug("[Feishu onboard] HTTP probe failed: %s", exc)
  3814. return None
  3815. def qr_register(*, initial_domain: str = "feishu", timeout_seconds: int = 600) -> Optional[dict]:
  3816. """Scan-to-create flow → {app_id, app_secret, domain, open_id, bot_name, bot_open_id}.
  3817. None on expected failures (network, denied, timeout); unexpected errors propagate.
  3818. """
  3819. try:
  3820. return _qr_register_inner(initial_domain=initial_domain, timeout_seconds=timeout_seconds)
  3821. except (RuntimeError, URLError, OSError, json.JSONDecodeError) as exc:
  3822. logger.warning("[Feishu onboard] Registration failed: %s", exc)
  3823. return None
  3824. def _qr_register_inner(*, initial_domain: str, timeout_seconds: int) -> Optional[dict]:
  3825. """Run init → begin → poll → probe. Raises on network/protocol errors."""
  3826. print(" Connecting to Feishu / Lark...", end="", flush=True)
  3827. _init_registration(initial_domain)
  3828. begin = _begin_registration(initial_domain)
  3829. print(" done.")
  3830. print()
  3831. qr_url = begin["qr_url"]
  3832. if _render_qr(qr_url):
  3833. print(f"\n Scan the QR code above, or open this URL directly:\n {qr_url}")
  3834. else:
  3835. print(f" Open this URL in Feishu / Lark on your phone:\n\n {qr_url}\n")
  3836. print(" Tip: from the Hermes environment, run: "
  3837. f"{install_hint('messaging')} "
  3838. "to display a scannable QR code here next time")
  3839. print()
  3840. result = _poll_registration(
  3841. device_code=begin["device_code"], interval=begin["interval"],
  3842. expire_in=min(begin["expire_in"], timeout_seconds), domain=initial_domain,
  3843. )
  3844. if not result:
  3845. return None
  3846. bot_info = probe_bot(result["app_id"], result["app_secret"], result["domain"]) or {} # best-effort
  3847. result["bot_name"] = bot_info.get("bot_name")
  3848. result["bot_open_id"] = bot_info.get("bot_open_id")
  3849. return result
  3850. # --- Plugin glue: register(ctx) + the hook fns that replaced the per-platform core touchpoints ---
  3851. # ────────────────────────────────────────────────────────────────────────── Plugin migration glue (#41112 /
  3852. # #3823) Added when the Feishu adapter (+ its feishu_comment / feishu_comment_rules / feishu_meeting_invite
  3853. # satellites) moved from gateway/platforms/ into this bundled plugin. Mirrors the Discord (#24356) / Slack
  3854. # migrations: a register(ctx) entry point plus hook implementations that replace the per-platform core
  3855. # touchpoints (the Platform.FEISHU elif in gateway/run.py, the feishu_cfg YAML→env block +
  3856. # _PLATFORM_CONNECTED_CHECKERS entry in gateway/config.py, the _setup_feishu wizard + _PLATFORMS["feishu"]
  3857. # static dict in hermes_cli/gateway.py, and the _send_feishu dispatch in tools/send_message_tool.py).
  3858. # ──────────────────────────────────────────────────────────────────────────
  3859. _MIGRATION_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
  3860. _MIGRATION_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
  3861. _MIGRATION_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"}
  3862. async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
  3863. """standalone_sender_fn: out-of-process delivery (cron without gateway) via a transient adapter."""
  3864. if not await asyncio.to_thread(_load_lark_oapi):
  3865. return send_error("Feishu dependencies not installed. Run `hermes setup` to install Feishu support.")
  3866. try:
  3867. adapter = FeishuAdapter(pconfig)
  3868. adapter._client = adapter._build_lark_client(_sdk_domain(getattr(adapter, "_domain_name", "feishu")))
  3869. metadata = {"thread_id": thread_id} if thread_id else None
  3870. last_result = None
  3871. if message.strip():
  3872. last_result = await adapter.send(chat_id, message, metadata=metadata)
  3873. if not last_result.success:
  3874. return send_error(f"Feishu send failed: {last_result.error}")
  3875. for media_path, _is_voice in media_files or []:
  3876. if not os.path.exists(media_path):
  3877. return send_error(f"Media file not found: {media_path}")
  3878. ext = os.path.splitext(media_path)[1].lower()
  3879. if ext in _MIGRATION_IMAGE_EXTS:
  3880. sender = adapter.send_image_file
  3881. elif ext in _MIGRATION_VIDEO_EXTS:
  3882. sender = adapter.send_video
  3883. elif ext in _MIGRATION_AUDIO_EXTS: # voice + non-voice audio both go out as voice
  3884. sender = adapter.send_voice
  3885. else:
  3886. sender = adapter.send_document
  3887. last_result = await sender(chat_id, media_path, metadata=metadata)
  3888. if not last_result.success:
  3889. return send_error(f"Feishu media send failed: {last_result.error}")
  3890. if last_result is None:
  3891. return send_error("No deliverable text or media remained after processing MEDIA tags")
  3892. return {"success": True, "platform": "feishu", "chat_id": chat_id, "message_id": last_result.message_id}
  3893. except Exception as e:
  3894. return send_error(f"Feishu send failed: {e}")
  3895. def interactive_setup() -> None:
  3896. """Interactive setup for Feishu / Lark — scan-to-create or manual creds (CLI helpers lazy-imported)."""
  3897. from hermes_cli.config import remove_env_value, save_env_value
  3898. from hermes_cli.setup import prompt_choice
  3899. from hermes_cli.cli_output import prompt, print_header, print_info, print_success, print_warning
  3900. from hermes_cli.setup_platforms import declines_reconfigure
  3901. print_header("Feishu / Lark")
  3902. if declines_reconfigure("Feishu / Lark", "Reconfigure Feishu / Lark?", "FEISHU_APP_ID"):
  3903. return
  3904. method_idx = prompt_choice(
  3905. "How would you like to set up Feishu / Lark?",
  3906. ["Scan QR code to create a new bot automatically (recommended)", "Enter existing App ID and App Secret manually"],
  3907. 0,
  3908. )
  3909. credentials = None
  3910. if method_idx == 0:
  3911. try:
  3912. credentials = qr_register()
  3913. except KeyboardInterrupt:
  3914. print_warning("Feishu / Lark setup cancelled.")
  3915. return
  3916. except Exception as exc:
  3917. print_warning(f"QR registration failed: {exc}")
  3918. if not credentials:
  3919. print_info("QR setup did not complete. Continuing with manual input.")
  3920. used_qr = bool(credentials)
  3921. if not credentials:
  3922. print_info("Go to https://open.feishu.cn/ (or https://open.larksuite.com/ for Lark)")
  3923. print_info("Create an app, enable the Bot capability, and copy the credentials.")
  3924. app_id = prompt("App ID", password=False)
  3925. if not app_id:
  3926. print_warning("Skipped — Feishu / Lark won't work without an App ID.")
  3927. return
  3928. app_secret = prompt("App Secret", password=True)
  3929. if not app_secret:
  3930. print_warning("Skipped — Feishu / Lark won't work without an App Secret.")
  3931. return
  3932. domain = "lark" if prompt_choice("Domain", ["feishu (China)", "lark (International)"], 0) == 1 else "feishu"
  3933. bot_name = None
  3934. try:
  3935. bot_info = probe_bot(app_id, app_secret, domain)
  3936. if bot_info:
  3937. bot_name = bot_info.get("bot_name")
  3938. print_success(f"Credentials verified — bot: {bot_name or 'unnamed'}")
  3939. else:
  3940. print_warning("Could not verify bot connection. Credentials saved anyway.")
  3941. except Exception as exc:
  3942. print_warning(f"Credential verification skipped: {exc}")
  3943. credentials = {"app_id": app_id, "app_secret": app_secret, "domain": domain, "open_id": None, "bot_name": bot_name}
  3944. app_id, app_secret = credentials["app_id"], credentials["app_secret"]
  3945. domain = credentials.get("domain", "feishu")
  3946. open_id, bot_name = credentials.get("open_id"), credentials.get("bot_name")
  3947. save_env_value("FEISHU_APP_ID", app_id)
  3948. save_env_value("FEISHU_APP_SECRET", app_secret)
  3949. save_env_value("FEISHU_DOMAIN", domain)
  3950. if used_qr:
  3951. connection_mode = "websocket"
  3952. else:
  3953. mode_idx = prompt_choice(
  3954. "Connection mode",
  3955. ["WebSocket (recommended — no public URL needed)", "Webhook (requires a reachable HTTP endpoint)"],
  3956. 0,
  3957. )
  3958. connection_mode = "webhook" if mode_idx == 1 else "websocket"
  3959. if connection_mode == "webhook":
  3960. print_info("Webhook defaults: 127.0.0.1:8765/feishu/webhook")
  3961. print_info("Override with FEISHU_WEBHOOK_HOST / FEISHU_WEBHOOK_PORT / FEISHU_WEBHOOK_PATH")
  3962. print_info("For signature verification, set FEISHU_ENCRYPT_KEY and FEISHU_VERIFICATION_TOKEN")
  3963. save_env_value("FEISHU_CONNECTION_MODE", connection_mode)
  3964. if bot_name:
  3965. print_success(f"Bot created: {bot_name}")
  3966. access_idx = prompt_choice(
  3967. "How should direct messages be authorized?",
  3968. ["Use DM pairing approval (recommended)", "Allow all direct messages", "Only allow listed user IDs"],
  3969. 0,
  3970. )
  3971. save_env_value("FEISHU_ALLOW_ALL_USERS", "true" if access_idx == 1 else "false")
  3972. if access_idx == 2:
  3973. allowlist = prompt("Allowed user IDs (comma-separated)", open_id or "", password=False).replace(" ", "")
  3974. save_env_value("FEISHU_ALLOWED_USERS", allowlist)
  3975. print_success("Allowlist saved.")
  3976. else:
  3977. save_env_value("FEISHU_ALLOWED_USERS", "")
  3978. if access_idx == 0:
  3979. print_success("DM pairing enabled.")
  3980. print_info("Unknown users can request access; approve with `hermes pairing approve`.")
  3981. else:
  3982. print_warning("Open DM access enabled for Feishu / Lark.")
  3983. group_idx = prompt_choice(
  3984. "How should group chats be handled?",
  3985. ["Respond only when @mentioned in groups (recommended)", "Disable group chats"], 0,
  3986. )
  3987. save_env_value("FEISHU_GROUP_POLICY", "open" if group_idx == 0 else "disabled")
  3988. print_info("Group chats enabled (bot must be @mentioned)." if group_idx == 0 else "Group chats disabled.")
  3989. print_info("Leave blank to clear a previously saved home channel (cron / notifications).")
  3990. home_channel = prompt("Home chat ID (optional, for cron/notifications)", password=False).strip()
  3991. if home_channel:
  3992. save_env_value("FEISHU_HOME_CHANNEL", home_channel)
  3993. print_success(f"Home channel set to {home_channel}")
  3994. elif remove_env_value("FEISHU_HOME_CHANNEL"):
  3995. print_info("Home channel cleared.")
  3996. print_success("🪽 Feishu / Lark configured!")
  3997. print_info(f"App ID: {app_id}")
  3998. print_info(f"Domain: {domain}")
  3999. if bot_name:
  4000. print_info(f"Bot: {bot_name}")
  4001. def _apply_yaml_config(yaml_cfg: dict, feishu_cfg: dict) -> dict | None:
  4002. """``apply_yaml_config_fn`` (#24849): bridge config.yaml feishu.allow_bots to FEISHU_ALLOW_BOTS (env wins) and
  4003. seed ``extra.allow_bots`` so a multiplexed secondary profile's adapter reads its own value."""
  4004. seeded = _apply_yaml_bridge(feishu_cfg, (("allow_bots", "FEISHU_ALLOW_BOTS", "lower"),))
  4005. return {"allow_bots": str(seeded["allow_bots"]).lower()} if seeded else None
  4006. def _is_connected(config) -> bool:
  4007. """Feishu counts as connected once app_id is configured."""
  4008. extra = getattr(config, "extra", {}) or {}
  4009. return bool(extra.get("app_id"))
  4010. def register(ctx) -> None:
  4011. """Plugin entry point — called by the Hermes plugin system."""
  4012. from .adapter_hint import PLATFORM_HINT
  4013. from .send_targets import SEND_ENTRY_KWARGS
  4014. from .dashboard_card import DASHBOARD_CARD
  4015. from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)
  4016. ctx.register_platform(
  4017. **SEND_ENTRY_KWARGS, # send_message target syntax + routing
  4018. name="feishu", label="Feishu / Lark", adapter_factory=FeishuAdapter,
  4019. **DASHBOARD_CARD,
  4020. check_fn=feishu_deps_present, ensure_deps_fn=check_feishu_requirements,
  4021. is_connected=_is_connected, validate_config=_is_connected,
  4022. required_env=["FEISHU_APP_ID", "FEISHU_APP_SECRET"],
  4023. install_hint="Run `hermes setup` to install Feishu support.", setup_fn=interactive_setup,
  4024. apply_yaml_config_fn=_apply_yaml_config, cron_deliver_env_var="FEISHU_HOME_CHANNEL",
  4025. standalone_sender_fn=_standalone_send, max_message_length=8000, emoji="🪽",
  4026. allow_update_command=True,
  4027. platform_hint=PLATFORM_HINT,
  4028. display_tier="medium",
  4029. env_overrides=gateway_env.ENV_OVERRIDES,
  4030. env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS, **gateway_env.AUTHZ,
  4031. )