group_orchestrator.py 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776
  1. """Async scheduler for durable YaoYao group Agent runs.
  2. The store is the concurrency authority. This module only owns process-local
  3. Gateway generations and moves every blocking SQLite/Gateway call off the
  4. Dashboard event loop.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. from contextlib import AsyncExitStack, asynccontextmanager
  9. from dataclasses import dataclass, field
  10. import json
  11. import logging
  12. import math
  13. import re
  14. import threading
  15. import uuid
  16. from typing import Any, Awaitable, Callable, Mapping, Protocol
  17. from .group_gateway import SessionIdentity
  18. from .group_remote_gateway import GroupGatewayRouter
  19. from .group_protocol import MAX_MESSAGE_BYTES, MAX_TOOL_STATE_BYTES
  20. logger = logging.getLogger(__name__)
  21. DEFAULT_EVENT_QUEUE_SIZE = 256
  22. DEFAULT_COMPLETION_TIMEOUT = 15 * 60.0
  23. STREAM_FLUSH_INTERVAL = 0.05
  24. _ERROR_TEXT_LIMIT = 4096
  25. _TOOL_VALUE_LIMIT = 16 * 1024
  26. _TOOL_TEXT_LIMIT = 4096
  27. _TOOL_FINDING_LIMIT = 32
  28. _TOOL_COUNT_LIMIT = 128
  29. _TOOL_TRUNCATION_ID = "__hermes_group_tool_state_truncated__"
  30. _TOOL_STATE_INTERNAL_LIMIT = min(MAX_TOOL_STATE_BYTES, 192 * 1024)
  31. _PERSISTED_EVENTS = frozenset(
  32. {
  33. "message.start",
  34. "message.delta",
  35. "message.complete",
  36. "reasoning.delta",
  37. "tool.start",
  38. "tool.complete",
  39. "tool.output_risk",
  40. "approval.request",
  41. "clarify.request",
  42. "clarify.expire",
  43. "session.info",
  44. "error",
  45. }
  46. )
  47. _TERMINAL_RUN_STATUSES = frozenset({"completed", "failed", "interrupted"})
  48. _APPROVAL_CHOICES = frozenset({"once", "session", "always", "deny"})
  49. _STORE_RETRY_DELAYS = (0.01, 0.02, 0.04)
  50. _CLAIM_RETRY_MAX_SECONDS = 1.0
  51. _WORK_DISABLED_RETRY_SECONDS = 1.0
  52. _NO_REPLY_TOKEN = "[[YAOYAO_NO_REPLY_V1]]"
  53. _NO_REPLY_RESERVED_PATTERN = re.compile(r"\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?")
  54. _HOST_FALLBACK_REPLY = (
  55. "我还不能确定你希望我处理什么,请补充具体目标、范围,或明确需要我协调的 Agent。"
  56. )
  57. def _is_no_reply_content(value: object) -> bool:
  58. return isinstance(value, str) and value.strip() == _NO_REPLY_TOKEN
  59. def _sanitize_no_reply_text(value: str) -> str:
  60. return _NO_REPLY_RESERVED_PATTERN.sub("", value)
  61. def _log_failure_type(message: str, error: BaseException) -> None:
  62. """Log stable context without persisting Gateway or Store exception text."""
  63. logger.error("%s [errorType=%s]", message, type(error).__name__)
  64. class GroupOrchestratorError(RuntimeError):
  65. """Raised for an invalid scheduler lifecycle or local runtime collision."""
  66. class _Store(Protocol):
  67. def initialize(self) -> None: ...
  68. def recover_after_restart(self) -> list[str]: ...
  69. def claim_next_runnable_run(self) -> dict[str, object] | None: ...
  70. def read_run_projection(self, run_id: str) -> dict[str, object]: ...
  71. def prepare_run_session_configuration(
  72. self, run_id: str, configuration: Mapping[str, object]
  73. ) -> bool: ...
  74. def bind_run_runtime(
  75. self, run_id: str, runtime_session_id: str
  76. ) -> dict[str, object]: ...
  77. def commit_prompt_submission(
  78. self, run_id: str, **kwargs: object
  79. ) -> dict[str, object]: ...
  80. def upsert_agent_message(
  81. self, run_id: str, **kwargs: object
  82. ) -> dict[str, object]: ...
  83. def settle_run(self, run_id: str, **kwargs: object) -> dict[str, object]: ...
  84. def transition_run(
  85. self, run_id: str, status: str, **kwargs: object
  86. ) -> dict[str, object]: ...
  87. def get_run(self, run_id: str) -> dict[str, object]: ...
  88. def get_message(self, message_id: str) -> dict[str, object]: ...
  89. def get_room(self, room_id: str) -> dict[str, object]: ...
  90. def get_interaction(self, interaction_id: str) -> dict[str, object]: ...
  91. def list_pending_cascades(self, **kwargs: object) -> dict[str, object]: ...
  92. def complete_cascade(self, source_run_id: str) -> dict[str, object]: ...
  93. def interrupt_agent_with_runtime_targets(
  94. self, room_id: str, agent_id: str, command: Mapping[str, object]
  95. ) -> dict[str, object]: ...
  96. def archive_room_with_runtime_targets(
  97. self, room_id: str, command: Mapping[str, object]
  98. ) -> dict[str, object]: ...
  99. def restore_room(self, room_id: str, command: Mapping[str, object]) -> dict[str, object]: ...
  100. def archive_topic(
  101. self, room_id: str, topic_id: str, command: Mapping[str, object]
  102. ) -> dict[str, object]: ...
  103. def restore_topic(
  104. self, room_id: str, topic_id: str, command: Mapping[str, object]
  105. ) -> dict[str, object]: ...
  106. def create_room(self, command: Mapping[str, object]) -> dict[str, object]: ...
  107. def update_room(
  108. self, room_id: str, command: Mapping[str, object]
  109. ) -> dict[str, object]: ...
  110. def update_topic(
  111. self, room_id: str, topic_id: str, command: Mapping[str, object]
  112. ) -> dict[str, object]: ...
  113. def mark_topic_read(
  114. self, room_id: str, topic_id: str, command: Mapping[str, object]
  115. ) -> dict[str, object]: ...
  116. def add_agent(
  117. self, room_id: str, command: Mapping[str, object]
  118. ) -> dict[str, object]: ...
  119. def update_agent_with_runtime_targets(
  120. self,
  121. room_id: str,
  122. agent_id: str,
  123. command: Mapping[str, object],
  124. ) -> dict[str, object]: ...
  125. def delete_agent_with_runtime_targets(
  126. self,
  127. room_id: str,
  128. agent_id: str,
  129. command: Mapping[str, object],
  130. ) -> dict[str, object]: ...
  131. def create_human_message(
  132. self,
  133. room_id: str,
  134. *,
  135. request_id: str,
  136. client_message_id: str,
  137. content: str,
  138. mention_agent_ids: list[str],
  139. topic_id: str | None = None,
  140. ) -> dict[str, object]: ...
  141. def create_gateway_interaction(
  142. self, run_id: str, **kwargs: object
  143. ) -> dict[str, object]: ...
  144. def expire_interaction(self, interaction_id: str) -> dict[str, object]: ...
  145. def begin_interaction_response(
  146. self, room_id: str, interaction_id: str, **kwargs: object
  147. ) -> dict[str, object]: ...
  148. def finish_interaction_response(
  149. self, request_id: str, **kwargs: object
  150. ) -> dict[str, object]: ...
  151. def fail_interaction_response(
  152. self, request_id: str, **kwargs: object
  153. ) -> dict[str, object]: ...
  154. class _Gateway(Protocol):
  155. transport: Any
  156. def create_session(
  157. self,
  158. profile: str,
  159. title: str,
  160. cwd: str,
  161. seed_messages: list[dict[str, Any]],
  162. configuration: dict[str, Any] | None = None,
  163. ) -> SessionIdentity: ...
  164. def resume_session(self, profile: str, stored_id: str) -> SessionIdentity: ...
  165. def submit_prompt(self, runtime_id: str, text: str) -> None: ...
  166. def interrupt(self, runtime_id: str) -> None: ...
  167. def close(self, runtime_id: str) -> bool: ...
  168. def respond_approval(self, runtime_id: str, choice: str) -> int: ...
  169. def respond_clarification(self, request_id: str, answer: str) -> str: ...
  170. def shutdown(self) -> None: ...
  171. GatewayFactory = Callable[[Callable[[str, str, dict[str, object]], None]], _Gateway]
  172. @dataclass(frozen=True)
  173. class _GatewayEvent:
  174. runtime_id: str
  175. generation: int
  176. event_type: str
  177. payload: dict[str, object]
  178. @dataclass
  179. class _RuntimeState:
  180. run_id: str
  181. room_id: str
  182. topic_id: str
  183. agent_id: str
  184. runtime_id: str
  185. generation: int
  186. expected_stored_id: str | None
  187. session_stored_id: str
  188. expected_context_seq: int
  189. through_seq: int
  190. profile: str = ""
  191. reply_mode: str = "mentioned"
  192. required_reply: bool = False
  193. automatic_published: bool = False
  194. had_visible_interaction: bool = False
  195. prompt_ready: asyncio.Event = field(default_factory=asyncio.Event)
  196. finished: asyncio.Event = field(default_factory=asyncio.Event)
  197. terminal_info_received: asyncio.Event = field(default_factory=asyncio.Event)
  198. finalize_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
  199. mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
  200. pending_events: asyncio.Queue[_GatewayEvent | None] = field(
  201. default_factory=lambda: asyncio.Queue(maxsize=64)
  202. )
  203. event_task: asyncio.Task[None] | None = None
  204. grace_task: asyncio.Task[None] | None = None
  205. inflight_calls: set[asyncio.Task[object]] = field(default_factory=set)
  206. mutation_tasks: set[asyncio.Task[dict[str, object]]] = field(default_factory=set)
  207. content: str = ""
  208. reasoning: str = ""
  209. tool_state: list[dict[str, object]] = field(default_factory=list)
  210. tool_indexes: dict[str, int] = field(default_factory=dict)
  211. clarification_ids: dict[str, str] = field(default_factory=dict)
  212. pending_interaction_ids: set[str] = field(default_factory=set)
  213. stream_dirty: bool = False
  214. last_stream_flush: float = 0.0
  215. approval_ordinal: int = 0
  216. complete_seen: bool = False
  217. complete_index: int = 0
  218. event_index: int = 0
  219. terminal_status: str | None = None
  220. terminal_error: str = ""
  221. actual_model: str | None = None
  222. actual_provider: str | None = None
  223. actual_reasoning_effort: str | None = None
  224. actual_fast_mode: bool | None = None
  225. settle_error: BaseException | None = None
  226. prompt_committed: bool = False
  227. overflowed: bool = False
  228. finalizing: bool = False
  229. @dataclass
  230. class _AgentLockState:
  231. lock: asyncio.Lock = field(default_factory=asyncio.Lock)
  232. users: int = 0
  233. def _required_mapping(value: object, field_name: str) -> Mapping[str, object]:
  234. if not isinstance(value, Mapping):
  235. raise GroupOrchestratorError(f"{field_name} must be an object")
  236. return value
  237. def _required_string(value: object, field_name: str) -> str:
  238. if not isinstance(value, str) or not value:
  239. raise GroupOrchestratorError(f"{field_name} must be a non-empty string")
  240. return value
  241. def _required_string_allowing_empty(value: object, field_name: str) -> str:
  242. if not isinstance(value, str):
  243. raise GroupOrchestratorError(f"{field_name} must be a string")
  244. return value
  245. def _optional_string(value: object, field_name: str) -> str | None:
  246. if value is None:
  247. return None
  248. return _required_string(value, field_name)
  249. def _required_nonnegative_int(value: object, field_name: str) -> int:
  250. if isinstance(value, bool) or not isinstance(value, int) or value < 0:
  251. raise GroupOrchestratorError(f"{field_name} must be a non-negative integer")
  252. return value
  253. def _required_bool(value: object, field_name: str) -> bool:
  254. if not isinstance(value, bool):
  255. raise GroupOrchestratorError(f"{field_name} must be a boolean")
  256. return value
  257. def _strict_json_copy(value: object, field_name: str) -> object:
  258. try:
  259. encoded = json.dumps(
  260. value,
  261. ensure_ascii=False,
  262. sort_keys=True,
  263. separators=(",", ":"),
  264. allow_nan=False,
  265. )
  266. encoded.encode("utf-8")
  267. return json.loads(encoded)
  268. except (TypeError, ValueError, UnicodeEncodeError, json.JSONDecodeError) as error:
  269. raise GroupOrchestratorError(f"{field_name} must be strict JSON") from error
  270. def build_run_prompt(
  271. projection: Mapping[str, object],
  272. room_agents: list[Mapping[str, object]] | None = None,
  273. ) -> str:
  274. """Build a deterministic prompt from the Store's bounded projection."""
  275. run = _required_mapping(projection.get("run"), "projection.run")
  276. room = _required_mapping(projection.get("room"), "projection.room")
  277. agent = _required_mapping(projection.get("agent"), "projection.agent")
  278. messages = projection.get("messages")
  279. if not isinstance(messages, list) or not all(
  280. isinstance(message, Mapping) for message in messages
  281. ):
  282. raise GroupOrchestratorError("projection.messages must be a list of objects")
  283. envelope = {
  284. "agent": {
  285. "displayName": _required_string(
  286. agent.get("displayName"), "projection.agent.displayName"
  287. ),
  288. "id": _required_string(agent.get("id"), "projection.agent.id"),
  289. "description": _required_string_allowing_empty(
  290. agent.get("description", ""), "projection.agent.description"
  291. ),
  292. "isHost": _required_bool(
  293. agent.get("isHost", False), "projection.agent.isHost"
  294. ),
  295. },
  296. "messages": _strict_json_copy(messages, "projection.messages"),
  297. "omittedSummary": _strict_json_copy(
  298. projection.get("omittedSummary"), "projection.omittedSummary"
  299. ),
  300. "room": {
  301. "id": _required_string(room.get("id"), "projection.room.id"),
  302. "name": _required_string(room.get("name"), "projection.room.name"),
  303. "instructions": _required_string_allowing_empty(
  304. room.get("instructions", ""), "projection.room.instructions"
  305. ),
  306. "maxReplyRounds": room.get("maxReplyRounds", 3),
  307. "orchestrationMode": _required_string(
  308. room.get("orchestrationMode", "free"),
  309. "projection.room.orchestrationMode",
  310. ),
  311. },
  312. "run": {
  313. "id": _required_string(run.get("id"), "projection.run.id"),
  314. "topicId": _required_string(
  315. run.get("topicId"), "projection.run.topicId"
  316. ),
  317. "rootMessageId": _required_string(
  318. run.get("rootMessageId"), "projection.run.rootMessageId"
  319. ),
  320. "triggerMessageId": _required_string(
  321. run.get("triggerMessageId"), "projection.run.triggerMessageId"
  322. ),
  323. "replyMode": _required_string(
  324. run.get("replyMode", "mentioned"), "projection.run.replyMode"
  325. ),
  326. "requiredReply": _required_bool(
  327. run.get("requiredReply", False), "projection.run.requiredReply"
  328. ),
  329. },
  330. "throughSeq": _required_nonnegative_int(
  331. projection.get("throughSeq"), "projection.throughSeq"
  332. ),
  333. "version": 1,
  334. }
  335. members: list[dict[str, str]] = []
  336. for candidate in room_agents or []:
  337. if candidate.get("enabled") is not True:
  338. continue
  339. members.append(
  340. {
  341. "displayName": _required_string(
  342. candidate.get("displayName"), "roomAgent.displayName"
  343. ),
  344. "id": _required_string(candidate.get("id"), "roomAgent.id"),
  345. }
  346. )
  347. members.sort(key=lambda item: (item["displayName"].casefold(), item["id"]))
  348. envelope["roomAgents"] = members
  349. encoded = json.dumps(
  350. envelope,
  351. ensure_ascii=False,
  352. sort_keys=True,
  353. separators=(",", ":"),
  354. allow_nan=False,
  355. )
  356. automatic_rule = ""
  357. host_flow = envelope["room"]["orchestrationMode"] == "host"
  358. if envelope["run"]["requiredReply"] and host_flow:
  359. automatic_rule = (
  360. "你持有本话题当前唯一发言令牌,必须公开处理。请根据最新上下文动态决定下一步:"
  361. "有依赖关系时只 @下一位成员;任务相互独立时可以同时使用多个精确 @显示名 或 @all,"
  362. "系统会并列执行并在整批结束后统一交还给你复核;"
  363. "若任务已经完成,直接给出最终答复且不要 @任何成员;也可以发起澄清请求。"
  364. "禁止保持静默,禁止输出任何 YAOYAO_NO_REPLY 标记。"
  365. )
  366. elif envelope["run"]["requiredReply"]:
  367. automatic_rule = (
  368. "你是本房间唯一管理员。该用户消息没有有效 @,你必须公开处理;"
  369. "禁止保持静默,禁止输出任何 YAOYAO_NO_REPLY 标记。必须三选一:"
  370. "直接回答;使用成员列表中的精确 @显示名 转派;或发起澄清请求。"
  371. )
  372. elif envelope["run"]["replyMode"] == "automatic":
  373. automatic_rule = (
  374. f"若触发内容与自己的职责无关,禁止调用工具、禁止@成员,且完整答复只能是"
  375. f"{_NO_REPLY_TOKEN};正常答复绝不能包含该标记。"
  376. )
  377. elif host_flow and not envelope["agent"]["isHost"]:
  378. automatic_rule = (
  379. "你正在执行管理员委派的当前步骤。只回答本步骤,不要 @任何成员;"
  380. "完成后系统会把结果交还管理员复核并决定下一步。"
  381. )
  382. collaboration_rule = (
  383. "管理员协调中只有管理员可以调度成员;成员可以按依赖串行,也可以成批并列执行。"
  384. if host_flow
  385. else "仅在确实需要成员协作时,使用成员列表中的精确 @显示名 或 @all 发起下一轮。"
  386. )
  387. instructions_rule = (
  388. "GROUP_CONTEXT_JSON.room.instructions 是本房间的长期说明、协作规则和形式准则;"
  389. "必须在本次答复和工具使用中遵守。\n"
  390. if envelope["room"]["instructions"]
  391. else ""
  392. )
  393. return (
  394. "你正在 Hermes 多设备群聊中回复。只输出要发送到公共房间的答复;"
  395. f"{collaboration_rule}\n"
  396. f"{instructions_rule}"
  397. f"{automatic_rule}\n"
  398. f"runId={envelope['run']['id']} roomId={envelope['room']['id']} "
  399. f"agentId={envelope['agent']['id']}\n"
  400. f"GROUP_CONTEXT_JSON={encoded}"
  401. )
  402. class GroupOrchestrator:
  403. """Drive Store-claimed runs through one process-local Gateway adapter."""
  404. def __init__(
  405. self,
  406. store: _Store,
  407. *,
  408. gateway_factory: GatewayFactory | None = None,
  409. work_enabled: Callable[[], bool] | None = None,
  410. event_queue_size: int = DEFAULT_EVENT_QUEUE_SIZE,
  411. completion_timeout: float = DEFAULT_COMPLETION_TIMEOUT,
  412. ) -> None:
  413. if (
  414. isinstance(event_queue_size, bool)
  415. or not isinstance(event_queue_size, int)
  416. or event_queue_size < 1
  417. ):
  418. raise ValueError("event_queue_size must be a positive integer")
  419. if (
  420. isinstance(completion_timeout, bool)
  421. or not isinstance(completion_timeout, (int, float))
  422. or not math.isfinite(completion_timeout)
  423. or completion_timeout <= 0
  424. ):
  425. raise ValueError("completion_timeout must be positive")
  426. self.store = store
  427. self._gateway_factory: GatewayFactory = (
  428. gateway_factory
  429. if gateway_factory is not None
  430. else lambda callback: GroupGatewayRouter(callback)
  431. )
  432. if work_enabled is not None and not callable(work_enabled):
  433. raise ValueError("work_enabled must be callable")
  434. self._work_enabled = work_enabled if work_enabled is not None else lambda: True
  435. self._event_queue_size = event_queue_size
  436. self._completion_timeout = float(completion_timeout)
  437. self._loop: asyncio.AbstractEventLoop | None = None
  438. self._loop_thread_id: int | None = None
  439. self._gateway: _Gateway | None = None
  440. self._event_queue: asyncio.Queue[_GatewayEvent | None] | None = None
  441. self._event_task: asyncio.Task[None] | None = None
  442. self._scheduler_task: asyncio.Task[None] | None = None
  443. self._run_tasks: set[asyncio.Task[None]] = set()
  444. self._control_tasks: set[asyncio.Task[dict[str, object]]] = set()
  445. self._wake_event: asyncio.Event | None = None
  446. self._shutdown_event: asyncio.Event | None = None
  447. self._shutdown_complete: asyncio.Event | None = None
  448. self._shutdown_error: BaseException | None = None
  449. self._durable_failures: list[GroupOrchestratorError] = []
  450. self._run_failures: list[BaseException] = []
  451. self._failure_lock = threading.Lock()
  452. self._lifecycle_lock: asyncio.Lock | None = None
  453. self._started = False
  454. self._closing = False
  455. self._scheduler_busy = False
  456. self._mapping_lock = threading.RLock()
  457. self._runtime_states: dict[str, tuple[int, _RuntimeState]] = {}
  458. self._next_generation = 0
  459. self._agent_locks: dict[str, _AgentLockState] = {}
  460. self._submission_locks: dict[str, _AgentLockState] = {}
  461. self._room_locks: dict[str, _AgentLockState] = {}
  462. @property
  463. def event_queue_capacity(self) -> int:
  464. return self._event_queue_size
  465. @property
  466. def active_run_count(self) -> int:
  467. return len(self._run_tasks)
  468. async def start(self) -> None:
  469. """Initialize/recover durable state before exposing any scheduler work."""
  470. if self._lifecycle_lock is None:
  471. self._lifecycle_lock = asyncio.Lock()
  472. async with self._lifecycle_lock:
  473. if self._started:
  474. return
  475. if self._closing:
  476. raise GroupOrchestratorError("Orchestrator is shutting down")
  477. self._loop = asyncio.get_running_loop()
  478. self._loop_thread_id = threading.get_ident()
  479. try:
  480. await self._run_owned_start_worker(
  481. self.store.initialize,
  482. task_name="yaoyao-group-store-initialize",
  483. )
  484. await self._run_owned_start_worker(
  485. self.store.recover_after_restart,
  486. task_name="yaoyao-group-store-recover",
  487. )
  488. self._event_queue = asyncio.Queue(maxsize=self._event_queue_size)
  489. self._wake_event = asyncio.Event()
  490. self._shutdown_event = asyncio.Event()
  491. self._shutdown_complete = asyncio.Event()
  492. self._shutdown_error = None
  493. self._durable_failures = []
  494. self._run_failures = []
  495. await self._run_owned_start_worker(
  496. self._gateway_factory,
  497. self._gateway_event_callback,
  498. task_name="yaoyao-group-gateway-create",
  499. adopt=lambda gateway: setattr(self, "_gateway", gateway),
  500. )
  501. self._event_task = asyncio.create_task(
  502. self._consume_events(), name="yaoyao-group-events"
  503. )
  504. await asyncio.sleep(0)
  505. self._scheduler_task = asyncio.create_task(
  506. self._scheduler(), name="yaoyao-group-scheduler"
  507. )
  508. await asyncio.sleep(0)
  509. self._started = True
  510. self.wake()
  511. except BaseException:
  512. await self._rollback_failed_start()
  513. raise
  514. async def _run_owned_start_worker(
  515. self,
  516. callback: Callable[..., object],
  517. *args: object,
  518. task_name: str,
  519. adopt: Callable[[object], None] | None = None,
  520. ) -> object:
  521. """Wait out cancellation so a startup worker cannot outlive ownership."""
  522. worker = asyncio.get_running_loop().create_task(
  523. asyncio.to_thread(callback, *args), name=task_name
  524. )
  525. cancellation: asyncio.CancelledError | None = None
  526. while not worker.done():
  527. try:
  528. await asyncio.shield(worker)
  529. except asyncio.CancelledError as error:
  530. if cancellation is None:
  531. cancellation = error
  532. try:
  533. result = worker.result()
  534. except BaseException:
  535. if cancellation is not None:
  536. raise cancellation
  537. raise
  538. if adopt is not None:
  539. adopt(result)
  540. if cancellation is not None:
  541. raise cancellation
  542. return result
  543. async def _rollback_failed_start(self) -> None:
  544. """Reverse a partial start without invoking normal settlement paths."""
  545. for task in (self._scheduler_task, self._event_task):
  546. if task is not None and not task.done():
  547. task.cancel()
  548. tasks = tuple(
  549. task
  550. for task in (self._scheduler_task, self._event_task)
  551. if task is not None
  552. )
  553. if tasks:
  554. await asyncio.gather(*tasks, return_exceptions=True)
  555. gateway = self._gateway
  556. if gateway is not None:
  557. drain: Callable[[float | None], object] | None = None
  558. try:
  559. transport = getattr(gateway, "transport", None)
  560. candidate = getattr(transport, "drain", None)
  561. if callable(candidate):
  562. drain = candidate
  563. except BaseException as error: # noqa: BLE001 - shutdown still runs
  564. _log_failure_type("Failed to inspect a partial Gateway startup", error)
  565. if callable(drain):
  566. try:
  567. await self._run_owned_start_worker(
  568. drain,
  569. None,
  570. task_name="yaoyao-group-gateway-rollback-drain",
  571. )
  572. except BaseException as error: # noqa: BLE001 - keep primary
  573. _log_failure_type(
  574. "Failed to drain a partial Gateway startup", error
  575. )
  576. try:
  577. await self._run_owned_start_worker(
  578. gateway.shutdown,
  579. task_name="yaoyao-group-gateway-rollback-shutdown",
  580. )
  581. except BaseException as error: # noqa: BLE001 - preserve primary
  582. _log_failure_type(
  583. "Failed to roll back YaoYao group Gateway startup", error
  584. )
  585. self._started = False
  586. self._gateway = None
  587. self._event_task = None
  588. self._scheduler_task = None
  589. self._event_queue = None
  590. self._wake_event = None
  591. self._shutdown_event = None
  592. self._shutdown_complete = None
  593. self._loop = None
  594. self._loop_thread_id = None
  595. def wake(self) -> None:
  596. """Idempotently signal that queued durable work may now be runnable."""
  597. loop = self._loop
  598. wake_event = self._wake_event
  599. if loop is None or wake_event is None or self._closing:
  600. return
  601. if threading.get_ident() == self._loop_thread_id:
  602. wake_event.set()
  603. return
  604. try:
  605. loop.call_soon_threadsafe(wake_event.set)
  606. except RuntimeError:
  607. return
  608. async def drain_once(self, *, timeout: float = 5.0) -> None:
  609. """Wake the scheduler and wait until its current durable work is idle."""
  610. if not self._started:
  611. raise GroupOrchestratorError("Orchestrator is not started")
  612. if timeout <= 0:
  613. raise ValueError("timeout must be positive")
  614. self.wake()
  615. async def wait_idle() -> None:
  616. while True:
  617. wake_event = self._wake_event
  618. event_queue = self._event_queue
  619. if (
  620. wake_event is not None
  621. and event_queue is not None
  622. and not wake_event.is_set()
  623. and not self._scheduler_busy
  624. and not self._run_tasks
  625. and event_queue.empty()
  626. ):
  627. return
  628. await asyncio.sleep(0.001)
  629. await asyncio.wait_for(wait_idle(), timeout=timeout)
  630. async def _tracked_control(
  631. self,
  632. operation: Callable[[], Awaitable[dict[str, object]]],
  633. *,
  634. task_name: str,
  635. failure_message: str,
  636. ) -> dict[str, object]:
  637. """Shield one accepted mutation and expose it to orderly shutdown."""
  638. if not self._started or self._closing:
  639. raise GroupOrchestratorError("Orchestrator is not accepting controls")
  640. task = asyncio.create_task(operation(), name=task_name)
  641. self._control_tasks.add(task)
  642. def finished(done: asyncio.Task[dict[str, object]]) -> None:
  643. self._control_tasks.discard(done)
  644. if done.cancelled():
  645. return
  646. try:
  647. error = done.exception()
  648. except asyncio.CancelledError:
  649. return
  650. if error is not None:
  651. _log_failure_type(failure_message, error)
  652. task.add_done_callback(finished)
  653. return await asyncio.shield(task)
  654. @staticmethod
  655. def _public_command(value: Mapping[str, object]) -> dict[str, object]:
  656. command = _strict_json_copy(value, "command")
  657. if not isinstance(command, dict):
  658. raise GroupOrchestratorError("command must be an object")
  659. _required_string(command.get("requestId"), "command.requestId")
  660. return command
  661. async def create_room(self, *, command: Mapping[str, object]) -> dict[str, object]:
  662. safe_command = self._public_command(command)
  663. request_id = str(safe_command["requestId"])
  664. return await self._tracked_control(
  665. lambda: self._create_room(safe_command),
  666. task_name=f"yaoyao-group-create-room-{request_id}",
  667. failure_message="YaoYao group room creation failed",
  668. )
  669. async def _create_room(self, command: Mapping[str, object]) -> dict[str, object]:
  670. result = await asyncio.to_thread(self.store.create_room, command)
  671. if not isinstance(result, Mapping):
  672. raise GroupOrchestratorError("Created room is invalid")
  673. self.wake()
  674. return dict(result)
  675. async def update_room(
  676. self, *, room_id: str, command: Mapping[str, object]
  677. ) -> dict[str, object]:
  678. _required_string(room_id, "roomId")
  679. safe_command = self._public_command(command)
  680. request_id = str(safe_command["requestId"])
  681. return await self._tracked_control(
  682. lambda: self._update_room(room_id, safe_command),
  683. task_name=f"yaoyao-group-update-room-{request_id}",
  684. failure_message="YaoYao group room update failed",
  685. )
  686. async def _update_room(
  687. self, room_id: str, command: Mapping[str, object]
  688. ) -> dict[str, object]:
  689. async with self._room_serial(room_id):
  690. result = await asyncio.to_thread(self.store.update_room, room_id, command)
  691. if not isinstance(result, Mapping):
  692. raise GroupOrchestratorError("Updated room is invalid")
  693. self.wake()
  694. return dict(result)
  695. async def update_topic(
  696. self, *, room_id: str, topic_id: str, command: Mapping[str, object]
  697. ) -> dict[str, object]:
  698. _required_string(room_id, "roomId")
  699. _required_string(topic_id, "topicId")
  700. safe_command = self._public_command(command)
  701. request_id = str(safe_command["requestId"])
  702. return await self._tracked_control(
  703. lambda: self._update_topic(room_id, topic_id, safe_command),
  704. task_name=f"yaoyao-group-update-topic-{request_id}",
  705. failure_message="YaoYao group topic update failed",
  706. )
  707. async def _update_topic(
  708. self, room_id: str, topic_id: str, command: Mapping[str, object]
  709. ) -> dict[str, object]:
  710. async with self._room_serial(room_id):
  711. result = await asyncio.to_thread(
  712. self.store.update_topic, room_id, topic_id, command
  713. )
  714. if not isinstance(result, Mapping):
  715. raise GroupOrchestratorError("Updated topic is invalid")
  716. self.wake()
  717. return dict(result)
  718. async def archive_topic(
  719. self, *, room_id: str, topic_id: str, request_id: str
  720. ) -> dict[str, object]:
  721. _required_string(room_id, "roomId")
  722. _required_string(topic_id, "topicId")
  723. _required_string(request_id, "requestId")
  724. return await self._tracked_control(
  725. lambda: self._archive_topic(room_id, topic_id, request_id),
  726. task_name=f"yaoyao-group-archive-topic-{request_id}",
  727. failure_message="YaoYao group topic archive failed",
  728. )
  729. async def _archive_topic(
  730. self, room_id: str, topic_id: str, request_id: str
  731. ) -> dict[str, object]:
  732. async with self._room_serial(room_id):
  733. with self._mapping_lock:
  734. states = sorted(
  735. (state for _generation, state in self._runtime_states.values()
  736. if state.room_id == room_id and state.topic_id == topic_id),
  737. key=lambda state: (state.agent_id, state.runtime_id, state.generation),
  738. )
  739. async with AsyncExitStack() as stack:
  740. for state in states:
  741. await stack.enter_async_context(self._submission_serial(state.agent_id))
  742. await stack.enter_async_context(state.mutation_lock)
  743. current_states = self._current_owned_states(states)
  744. envelope = await self._run_states_blocking(
  745. current_states, self.store.archive_topic, room_id, topic_id,
  746. {"requestId": request_id},
  747. )
  748. if not isinstance(envelope, Mapping):
  749. raise GroupOrchestratorError("Archived topic is invalid")
  750. result = dict(envelope)
  751. if result.get("id") != topic_id or result.get("archived") is not True:
  752. raise GroupOrchestratorError("Archived topic identity changed")
  753. self.wake()
  754. cleanup_errors = await self._cleanup_lifecycle_targets_locked(
  755. current_states, tuple(), room_id=room_id, topic_id=topic_id,
  756. )
  757. if cleanup_errors:
  758. raise GroupOrchestratorError(
  759. "Topic was archived durably, but Gateway cleanup failed: "
  760. + "; ".join(cleanup_errors)
  761. )
  762. return result
  763. async def restore_topic(
  764. self, *, room_id: str, topic_id: str, request_id: str
  765. ) -> dict[str, object]:
  766. return await self._topic_lifecycle(
  767. room_id, topic_id, request_id, self.store.restore_topic, "restore"
  768. )
  769. async def restore_room(
  770. self, *, room_id: str, request_id: str
  771. ) -> dict[str, object]:
  772. _required_string(room_id, "roomId")
  773. _required_string(request_id, "requestId")
  774. async with self._room_serial(room_id):
  775. result = await asyncio.to_thread(
  776. self.store.restore_room, room_id, {"requestId": request_id}
  777. )
  778. if not isinstance(result, Mapping):
  779. raise GroupOrchestratorError("Restored room is invalid")
  780. self.wake()
  781. return dict(result)
  782. async def _topic_lifecycle(
  783. self, room_id: str, topic_id: str, request_id: str,
  784. function: Callable[..., object], label: str,
  785. ) -> dict[str, object]:
  786. _required_string(room_id, "roomId")
  787. _required_string(topic_id, "topicId")
  788. _required_string(request_id, "requestId")
  789. async with self._room_serial(room_id):
  790. result = await asyncio.to_thread(
  791. function, room_id, topic_id, {"requestId": request_id}
  792. )
  793. if not isinstance(result, Mapping):
  794. raise GroupOrchestratorError(f"{label.title()}d topic is invalid")
  795. self.wake()
  796. return dict(result)
  797. async def mark_topic_read(
  798. self, *, room_id: str, topic_id: str, command: Mapping[str, object]
  799. ) -> dict[str, object]:
  800. _required_string(room_id, "roomId")
  801. _required_string(topic_id, "topicId")
  802. safe_command = self._public_command(command)
  803. request_id = str(safe_command["requestId"])
  804. return await self._tracked_control(
  805. lambda: self._mark_topic_read(room_id, topic_id, safe_command),
  806. task_name=f"yaoyao-group-mark-topic-read-{request_id}",
  807. failure_message="YaoYao group topic read update failed",
  808. )
  809. async def _mark_topic_read(
  810. self, room_id: str, topic_id: str, command: Mapping[str, object]
  811. ) -> dict[str, object]:
  812. async with self._room_serial(room_id):
  813. result = await asyncio.to_thread(
  814. self.store.mark_topic_read, room_id, topic_id, command
  815. )
  816. if not isinstance(result, Mapping):
  817. raise GroupOrchestratorError("Topic read response is invalid")
  818. self.wake()
  819. return dict(result)
  820. async def add_agent(
  821. self, *, room_id: str, command: Mapping[str, object]
  822. ) -> dict[str, object]:
  823. _required_string(room_id, "roomId")
  824. safe_command = self._public_command(command)
  825. request_id = str(safe_command["requestId"])
  826. return await self._tracked_control(
  827. lambda: self._add_agent(room_id, safe_command),
  828. task_name=f"yaoyao-group-add-agent-{request_id}",
  829. failure_message="YaoYao group Agent creation failed",
  830. )
  831. async def _add_agent(
  832. self, room_id: str, command: Mapping[str, object]
  833. ) -> dict[str, object]:
  834. async with self._room_serial(room_id):
  835. result = await asyncio.to_thread(self.store.add_agent, room_id, command)
  836. if not isinstance(result, Mapping):
  837. raise GroupOrchestratorError("Created Agent is invalid")
  838. self.wake()
  839. return dict(result)
  840. async def update_agent(
  841. self,
  842. *,
  843. room_id: str,
  844. agent_id: str,
  845. command: Mapping[str, object],
  846. ) -> dict[str, object]:
  847. _required_string(room_id, "roomId")
  848. _required_string(agent_id, "agentId")
  849. safe_command = self._public_command(command)
  850. request_id = str(safe_command["requestId"])
  851. return await self._tracked_control(
  852. lambda: self._mutate_agent(
  853. room_id=room_id,
  854. agent_id=agent_id,
  855. command=safe_command,
  856. operation="update",
  857. ),
  858. task_name=f"yaoyao-group-update-agent-{request_id}",
  859. failure_message="YaoYao group Agent update failed",
  860. )
  861. async def delete_agent(
  862. self,
  863. *,
  864. room_id: str,
  865. agent_id: str,
  866. request_id: str,
  867. ) -> dict[str, object]:
  868. _required_string(room_id, "roomId")
  869. _required_string(agent_id, "agentId")
  870. _required_string(request_id, "requestId")
  871. return await self._tracked_control(
  872. lambda: self._mutate_agent(
  873. room_id=room_id,
  874. agent_id=agent_id,
  875. command={"requestId": request_id},
  876. operation="delete",
  877. ),
  878. task_name=f"yaoyao-group-delete-agent-{request_id}",
  879. failure_message="YaoYao group Agent deletion failed",
  880. )
  881. async def _mutate_agent(
  882. self,
  883. *,
  884. room_id: str,
  885. agent_id: str,
  886. command: Mapping[str, object],
  887. operation: str,
  888. ) -> dict[str, object]:
  889. if operation == "update":
  890. store_method = self.store.update_agent_with_runtime_targets
  891. elif operation == "delete":
  892. store_method = self.store.delete_agent_with_runtime_targets
  893. else:
  894. raise GroupOrchestratorError("Unknown Agent mutation")
  895. async with self._room_serial(room_id):
  896. async with AsyncExitStack() as stack:
  897. await stack.enter_async_context(self._submission_serial(agent_id))
  898. with self._mapping_lock:
  899. states = sorted(
  900. (
  901. state
  902. for _generation, state in self._runtime_states.values()
  903. if state.room_id == room_id and state.agent_id == agent_id
  904. ),
  905. key=lambda state: (state.runtime_id, state.generation),
  906. )
  907. for state in states:
  908. await stack.enter_async_context(state.mutation_lock)
  909. current_states = self._current_owned_states(states)
  910. envelope = await self._run_states_blocking(
  911. current_states,
  912. store_method,
  913. room_id,
  914. agent_id,
  915. command,
  916. )
  917. result, runtime_ids = self._validated_lifecycle_envelope(
  918. envelope, f"agent.{operation}"
  919. )
  920. if result.get("id") != agent_id or result.get("roomId") != room_id:
  921. raise GroupOrchestratorError("Mutated Agent identity changed")
  922. if operation == "update":
  923. requested_enabled = command.get("enabled")
  924. if "enabled" in command and (
  925. not isinstance(requested_enabled, bool)
  926. or result.get("enabled") is not requested_enabled
  927. ):
  928. raise GroupOrchestratorError(
  929. "Updated Agent enabled state changed"
  930. )
  931. if requested_enabled is not False and runtime_ids:
  932. raise GroupOrchestratorError(
  933. "Non-disabling Agent update returned runtime targets"
  934. )
  935. self.wake()
  936. cleanup_errors = await self._cleanup_lifecycle_targets_locked(
  937. current_states,
  938. runtime_ids,
  939. room_id=room_id,
  940. agent_id=agent_id,
  941. )
  942. if cleanup_errors:
  943. raise GroupOrchestratorError(
  944. "Agent changed durably, but Gateway cleanup failed: "
  945. + "; ".join(cleanup_errors)
  946. )
  947. return result
  948. async def send_message(
  949. self,
  950. *,
  951. room_id: str,
  952. request_id: str,
  953. client_message_id: str,
  954. content: str,
  955. mention_agent_ids: list[str],
  956. topic_id: str | None = None,
  957. ) -> dict[str, object]:
  958. _required_string(room_id, "roomId")
  959. _required_string(request_id, "requestId")
  960. _required_string(client_message_id, "clientMessageId")
  961. if not isinstance(content, str):
  962. raise GroupOrchestratorError("content must be a string")
  963. if not isinstance(mention_agent_ids, list):
  964. raise GroupOrchestratorError("mentionAgentIds must be a list")
  965. if topic_id is not None:
  966. _required_string(topic_id, "topicId")
  967. safe_mentions = [
  968. _required_string(item, "mentionAgentIds") for item in mention_agent_ids
  969. ]
  970. return await self._tracked_control(
  971. lambda: self._send_message(
  972. room_id=room_id,
  973. request_id=request_id,
  974. client_message_id=client_message_id,
  975. content=content,
  976. mention_agent_ids=safe_mentions,
  977. topic_id=topic_id,
  978. ),
  979. task_name=f"yaoyao-group-send-{request_id}",
  980. failure_message="YaoYao group message submission failed",
  981. )
  982. async def _send_message(
  983. self,
  984. *,
  985. room_id: str,
  986. request_id: str,
  987. client_message_id: str,
  988. content: str,
  989. mention_agent_ids: list[str],
  990. topic_id: str | None,
  991. ) -> dict[str, object]:
  992. async with self._room_serial(room_id):
  993. async with AsyncExitStack() as stack:
  994. for agent_id in sorted(set(mention_agent_ids)):
  995. await stack.enter_async_context(self._submission_serial(agent_id))
  996. result = await asyncio.to_thread(
  997. self.store.create_human_message,
  998. room_id,
  999. request_id=request_id,
  1000. client_message_id=client_message_id,
  1001. content=content,
  1002. mention_agent_ids=mention_agent_ids,
  1003. topic_id=topic_id,
  1004. )
  1005. if not isinstance(result, Mapping):
  1006. raise GroupOrchestratorError("Created message is invalid")
  1007. self.wake()
  1008. return dict(result)
  1009. async def interrupt_agent(
  1010. self,
  1011. *,
  1012. room_id: str,
  1013. agent_id: str,
  1014. request_id: str,
  1015. ) -> dict[str, object]:
  1016. """Durably interrupt one Agent, then clean only owned Gateway generations."""
  1017. _required_string(room_id, "roomId")
  1018. _required_string(agent_id, "agentId")
  1019. _required_string(request_id, "requestId")
  1020. if not self._started or self._closing:
  1021. raise GroupOrchestratorError("Orchestrator is not accepting controls")
  1022. task = asyncio.create_task(
  1023. self._interrupt_agent(
  1024. room_id=room_id,
  1025. agent_id=agent_id,
  1026. request_id=request_id,
  1027. ),
  1028. name=f"yaoyao-group-interrupt-{request_id}",
  1029. )
  1030. self._control_tasks.add(task)
  1031. def finished(done: asyncio.Task[dict[str, object]]) -> None:
  1032. self._control_tasks.discard(done)
  1033. if done.cancelled():
  1034. return
  1035. try:
  1036. error = done.exception()
  1037. except asyncio.CancelledError:
  1038. return
  1039. if error is not None:
  1040. _log_failure_type("YaoYao group Agent interrupt failed", error)
  1041. task.add_done_callback(finished)
  1042. return await asyncio.shield(task)
  1043. async def archive_room(
  1044. self,
  1045. *,
  1046. room_id: str,
  1047. request_id: str,
  1048. ) -> dict[str, object]:
  1049. """Archive one room durably before cleaning its owned runtimes."""
  1050. _required_string(room_id, "roomId")
  1051. _required_string(request_id, "requestId")
  1052. return await self._tracked_control(
  1053. lambda: self._archive_room(room_id=room_id, request_id=request_id),
  1054. task_name=f"yaoyao-group-archive-{request_id}",
  1055. failure_message="YaoYao group room archive failed",
  1056. )
  1057. async def _archive_room(
  1058. self,
  1059. *,
  1060. room_id: str,
  1061. request_id: str,
  1062. ) -> dict[str, object]:
  1063. async with self._room_serial(room_id):
  1064. room = await asyncio.to_thread(
  1065. self.store.get_room, room_id, include_archived=True
  1066. )
  1067. agents = room.get("agents") if isinstance(room, Mapping) else None
  1068. if not isinstance(agents, list):
  1069. raise GroupOrchestratorError("room.agents must be a list")
  1070. agent_ids = sorted(
  1071. {
  1072. _required_string(
  1073. agent.get("id") if isinstance(agent, Mapping) else None,
  1074. "room.agent.id",
  1075. )
  1076. for agent in agents
  1077. }
  1078. )
  1079. async with AsyncExitStack() as stack:
  1080. for agent_id in agent_ids:
  1081. await stack.enter_async_context(self._submission_serial(agent_id))
  1082. with self._mapping_lock:
  1083. states = sorted(
  1084. (
  1085. state
  1086. for _generation, state in self._runtime_states.values()
  1087. if state.room_id == room_id
  1088. ),
  1089. key=lambda state: (
  1090. state.agent_id,
  1091. state.runtime_id,
  1092. state.generation,
  1093. ),
  1094. )
  1095. for state in states:
  1096. await stack.enter_async_context(state.mutation_lock)
  1097. current_states = self._current_owned_states(states)
  1098. envelope = await self._run_states_blocking(
  1099. current_states,
  1100. self.store.archive_room_with_runtime_targets,
  1101. room_id,
  1102. {"requestId": request_id},
  1103. )
  1104. result, runtime_ids = self._validated_lifecycle_envelope(
  1105. envelope, "archive"
  1106. )
  1107. if result.get("id") != room_id or result.get("archived") is not True:
  1108. raise GroupOrchestratorError("Archived room identity changed")
  1109. self.wake()
  1110. cleanup_errors = await self._cleanup_lifecycle_targets_locked(
  1111. current_states,
  1112. runtime_ids,
  1113. room_id=room_id,
  1114. )
  1115. if cleanup_errors:
  1116. raise GroupOrchestratorError(
  1117. "Room was archived durably, but Gateway cleanup failed: "
  1118. + "; ".join(cleanup_errors)
  1119. )
  1120. return result
  1121. def _current_owned_states(self, states: list[_RuntimeState]) -> list[_RuntimeState]:
  1122. current_states: list[_RuntimeState] = []
  1123. with self._mapping_lock:
  1124. for state in states:
  1125. if self._runtime_states.get(state.runtime_id) == (
  1126. state.generation,
  1127. state,
  1128. ):
  1129. current_states.append(state)
  1130. return current_states
  1131. @staticmethod
  1132. def _validated_lifecycle_envelope(
  1133. value: object, field_name: str
  1134. ) -> tuple[dict[str, object], tuple[str, ...]]:
  1135. envelope = _required_mapping(value, field_name)
  1136. result = _required_mapping(envelope.get("result"), f"{field_name}.result")
  1137. raw_runtime_ids = envelope.get("runtimeSessionIds")
  1138. if not isinstance(raw_runtime_ids, list) or len(raw_runtime_ids) > 8:
  1139. raise GroupOrchestratorError(
  1140. f"{field_name}.runtimeSessionIds must be a bounded list"
  1141. )
  1142. runtime_ids = tuple(
  1143. _required_string(item, f"{field_name}.runtimeSessionIds")
  1144. for item in raw_runtime_ids
  1145. )
  1146. if len(set(runtime_ids)) != len(runtime_ids):
  1147. raise GroupOrchestratorError(
  1148. f"{field_name}.runtimeSessionIds contains duplicates"
  1149. )
  1150. return dict(result), runtime_ids
  1151. async def _cleanup_lifecycle_targets_locked(
  1152. self,
  1153. states: list[_RuntimeState],
  1154. runtime_ids: tuple[str, ...],
  1155. *,
  1156. room_id: str,
  1157. agent_id: str | None = None,
  1158. topic_id: str | None = None,
  1159. ) -> list[str]:
  1160. owned = {
  1161. state.runtime_id: state
  1162. for state in states
  1163. if state.room_id == room_id
  1164. and (agent_id is None or state.agent_id == agent_id)
  1165. and (topic_id is None or state.topic_id == topic_id)
  1166. }
  1167. cleanup_errors: list[str] = []
  1168. replay_runtime_ids = set(runtime_ids)
  1169. ordered_runtime_ids = list(runtime_ids)
  1170. ordered_runtime_ids.extend(
  1171. runtime_id
  1172. for runtime_id in sorted(owned)
  1173. if runtime_id not in replay_runtime_ids
  1174. )
  1175. for runtime_id in ordered_runtime_ids:
  1176. state = owned.get(runtime_id)
  1177. if state is None:
  1178. continue
  1179. with self._mapping_lock:
  1180. current = self._runtime_states.get(runtime_id)
  1181. if current != (state.generation, state):
  1182. continue
  1183. try:
  1184. durable_run = await self._run_state_blocking(
  1185. state, self.store.get_run, state.run_id
  1186. )
  1187. except Exception: # noqa: BLE001 - never clean an unverified owner
  1188. cleanup_errors.append(f"verify {runtime_id}")
  1189. continue
  1190. if (
  1191. not isinstance(durable_run, Mapping)
  1192. or durable_run.get("status") not in _TERMINAL_RUN_STATUSES
  1193. or durable_run.get("runtimeSessionId") is not None
  1194. ):
  1195. # The idempotency replay may name a runtime id that has since
  1196. # been reused by a newer generation. Never clean that owner.
  1197. continue
  1198. error = await self._close_durably_interrupted_state_locked(state)
  1199. if error:
  1200. cleanup_errors.append(error)
  1201. return cleanup_errors
  1202. async def _interrupt_agent(
  1203. self,
  1204. *,
  1205. room_id: str,
  1206. agent_id: str,
  1207. request_id: str,
  1208. ) -> dict[str, object]:
  1209. async with self._submission_serial(agent_id):
  1210. with self._mapping_lock:
  1211. states = sorted(
  1212. (
  1213. state
  1214. for _generation, state in self._runtime_states.values()
  1215. if state.room_id == room_id and state.agent_id == agent_id
  1216. ),
  1217. key=lambda state: (state.runtime_id, state.generation),
  1218. )
  1219. async with AsyncExitStack() as stack:
  1220. for state in states:
  1221. await stack.enter_async_context(state.mutation_lock)
  1222. current_states: list[_RuntimeState] = []
  1223. with self._mapping_lock:
  1224. for state in states:
  1225. if self._runtime_states.get(state.runtime_id) == (
  1226. state.generation,
  1227. state,
  1228. ):
  1229. current_states.append(state)
  1230. if any(
  1231. state.finalizing and state.settle_error is not None
  1232. for state in current_states
  1233. ):
  1234. raise GroupOrchestratorError("Agent runtime is already finalizing")
  1235. envelope = await self._run_states_blocking(
  1236. current_states,
  1237. self.store.interrupt_agent_with_runtime_targets,
  1238. room_id,
  1239. agent_id,
  1240. {"requestId": request_id},
  1241. )
  1242. result, run_ids, runtime_ids = self._validated_interrupt_envelope(
  1243. envelope,
  1244. room_id=room_id,
  1245. agent_id=agent_id,
  1246. )
  1247. cleanup_errors: list[str] = []
  1248. for runtime_id in runtime_ids:
  1249. with self._mapping_lock:
  1250. current = self._runtime_states.get(runtime_id)
  1251. if current is None:
  1252. continue
  1253. generation, state = current
  1254. if (
  1255. state not in current_states
  1256. or generation != state.generation
  1257. or state.room_id != room_id
  1258. or state.agent_id != agent_id
  1259. or state.run_id not in run_ids
  1260. ):
  1261. # A replayed target must never affect a reused runtime id.
  1262. continue
  1263. error = await self._close_durably_interrupted_state_locked(state)
  1264. if error:
  1265. cleanup_errors.append(error)
  1266. if cleanup_errors:
  1267. raise GroupOrchestratorError(
  1268. "Agent was interrupted durably, but Gateway cleanup failed: "
  1269. + "; ".join(cleanup_errors)
  1270. )
  1271. return result
  1272. @staticmethod
  1273. def _validated_interrupt_envelope(
  1274. value: object,
  1275. *,
  1276. room_id: str,
  1277. agent_id: str,
  1278. ) -> tuple[dict[str, object], set[str], tuple[str, ...]]:
  1279. envelope = _required_mapping(value, "interrupt")
  1280. result_value = _required_mapping(envelope.get("result"), "interrupt.result")
  1281. if (
  1282. result_value.get("roomId") != room_id
  1283. or result_value.get("agentId") != agent_id
  1284. ):
  1285. raise GroupOrchestratorError("Interrupt scope changed")
  1286. def string_list(raw: object, field_name: str) -> tuple[str, ...]:
  1287. if not isinstance(raw, list) or len(raw) > 8:
  1288. raise GroupOrchestratorError(f"{field_name} must be a bounded list")
  1289. values = tuple(_required_string(item, field_name) for item in raw)
  1290. if len(set(values)) != len(values):
  1291. raise GroupOrchestratorError(f"{field_name} contains duplicates")
  1292. return values
  1293. run_ids = string_list(
  1294. result_value.get("interruptedRunIds"),
  1295. "interrupt.result.interruptedRunIds",
  1296. )
  1297. runtime_ids = string_list(
  1298. envelope.get("runtimeSessionIds"),
  1299. "interrupt.runtimeSessionIds",
  1300. )
  1301. return dict(result_value), set(run_ids), runtime_ids
  1302. async def _close_durably_interrupted_state_locked(
  1303. self, state: _RuntimeState
  1304. ) -> str | None:
  1305. async with state.finalize_lock:
  1306. with self._mapping_lock:
  1307. current = self._runtime_states.get(state.runtime_id)
  1308. if current != (state.generation, state):
  1309. return None
  1310. state.finalizing = True
  1311. failures: list[str] = []
  1312. gateway = self._required_gateway()
  1313. try:
  1314. await self._run_state_blocking(
  1315. state, gateway.interrupt, state.runtime_id
  1316. )
  1317. except Exception: # noqa: BLE001 - close is still required
  1318. failures.append(f"interrupt {state.runtime_id}")
  1319. closed = False
  1320. try:
  1321. closed = (
  1322. await self._run_state_blocking(
  1323. state, gateway.close, state.runtime_id
  1324. )
  1325. is True
  1326. )
  1327. if not closed:
  1328. failures.append(f"close {state.runtime_id}")
  1329. except Exception: # noqa: BLE001 - durable state already won
  1330. failures.append(f"close {state.runtime_id}")
  1331. if closed:
  1332. self._remove_runtime(state)
  1333. state.settle_error = None
  1334. state.finished.set()
  1335. state.terminal_info_received.set()
  1336. state.pending_interaction_ids.clear()
  1337. current_task = asyncio.current_task()
  1338. for helper in (state.event_task, state.grace_task):
  1339. if helper is None or helper is current_task:
  1340. continue
  1341. if not helper.done():
  1342. helper.cancel()
  1343. await asyncio.gather(helper, return_exceptions=True)
  1344. return ", ".join(failures) or None
  1345. async def respond_approval(
  1346. self,
  1347. *,
  1348. room_id: str,
  1349. interaction_id: str,
  1350. request_id: str,
  1351. choice: str,
  1352. permanent: bool,
  1353. ) -> dict[str, object]:
  1354. if not self._started or self._closing:
  1355. raise GroupOrchestratorError("Orchestrator is not accepting controls")
  1356. if choice not in _APPROVAL_CHOICES:
  1357. raise ValueError("choice must be once, session, always, or deny")
  1358. if not isinstance(permanent, bool) or ((choice == "always") != permanent):
  1359. raise ValueError("permanent must be true exactly for choice=always")
  1360. replay = await self._terminal_interaction_replay(
  1361. room_id=room_id,
  1362. interaction_id=interaction_id,
  1363. request_id=request_id,
  1364. kind="approval",
  1365. response={"choice": choice, "permanent": permanent},
  1366. )
  1367. if replay is not None:
  1368. return replay
  1369. state, interaction = await self._interaction_runtime(
  1370. room_id, interaction_id, "approval"
  1371. )
  1372. task = asyncio.create_task(
  1373. self._respond_approval_for_runtime(
  1374. state=state,
  1375. interaction=interaction,
  1376. room_id=room_id,
  1377. interaction_id=interaction_id,
  1378. request_id=request_id,
  1379. choice=choice,
  1380. permanent=permanent,
  1381. ),
  1382. name=f"yaoyao-group-approval-{request_id}",
  1383. )
  1384. self._track_mutation_task(state, task)
  1385. return await asyncio.shield(task)
  1386. async def _respond_approval_for_runtime(
  1387. self,
  1388. *,
  1389. state: _RuntimeState,
  1390. interaction: Mapping[str, object],
  1391. room_id: str,
  1392. interaction_id: str,
  1393. request_id: str,
  1394. choice: str,
  1395. permanent: bool,
  1396. ) -> dict[str, object]:
  1397. async with state.mutation_lock:
  1398. self._require_current_runtime(state)
  1399. claim = await self._run_state_blocking(
  1400. state,
  1401. self.store.begin_interaction_response,
  1402. room_id,
  1403. interaction_id,
  1404. request_id=request_id,
  1405. kind="approval",
  1406. response={"choice": choice, "permanent": permanent},
  1407. )
  1408. if not isinstance(claim, Mapping):
  1409. raise GroupOrchestratorError("Approval claim is invalid")
  1410. if claim.get("state") in {"replay", "failed"}:
  1411. response = claim.get("response")
  1412. return dict(response) if isinstance(response, Mapping) else dict(claim)
  1413. payload = interaction.get("payload")
  1414. choices = payload.get("choices") if isinstance(payload, Mapping) else None
  1415. if (
  1416. not isinstance(choices, list)
  1417. or choice not in choices
  1418. or not all(item in _APPROVAL_CHOICES for item in choices)
  1419. ):
  1420. await self._run_state_blocking(
  1421. state,
  1422. self.store.fail_interaction_response,
  1423. request_id,
  1424. reason="Approval choice is not allowed by the pending card",
  1425. uncertain=False,
  1426. )
  1427. raise ValueError("choice is not allowed by the pending approval")
  1428. try:
  1429. resolved = await self._run_state_blocking(
  1430. state,
  1431. self._required_gateway().respond_approval,
  1432. state.runtime_id,
  1433. choice,
  1434. )
  1435. except Exception:
  1436. await self._fail_unknown_interaction_response_locked(
  1437. state, request_id, "Gateway approval outcome is unknown"
  1438. )
  1439. raise GroupOrchestratorError("Gateway approval outcome is unknown")
  1440. if (
  1441. isinstance(resolved, bool)
  1442. or not isinstance(resolved, int)
  1443. or resolved not in {0, 1}
  1444. ):
  1445. await self._fail_unknown_interaction_response_locked(
  1446. state, request_id, "Gateway approval result is invalid"
  1447. )
  1448. raise GroupOrchestratorError("Gateway approval result is invalid")
  1449. public = {
  1450. "accepted": resolved == 1,
  1451. "interactionId": interaction_id,
  1452. }
  1453. try:
  1454. result = await self._store_retry(
  1455. state,
  1456. self.store.finish_interaction_response,
  1457. request_id,
  1458. response=public,
  1459. interaction_status=("resolved" if resolved == 1 else "cancelled"),
  1460. )
  1461. except Exception:
  1462. await self._finalize_state_locked(
  1463. state,
  1464. outcome="failed",
  1465. error="Durable approval response could not be completed",
  1466. interrupt=True,
  1467. )
  1468. raise
  1469. state.pending_interaction_ids.discard(interaction_id)
  1470. return dict(result)
  1471. async def respond_clarification(
  1472. self,
  1473. *,
  1474. room_id: str,
  1475. interaction_id: str,
  1476. request_id: str,
  1477. response: str,
  1478. ) -> dict[str, object]:
  1479. if not self._started or self._closing:
  1480. raise GroupOrchestratorError("Orchestrator is not accepting controls")
  1481. if not isinstance(response, str) or not response.strip():
  1482. raise ValueError("response must not be blank")
  1483. self._bounded_text(response, "clarification response")
  1484. replay = await self._terminal_interaction_replay(
  1485. room_id=room_id,
  1486. interaction_id=interaction_id,
  1487. request_id=request_id,
  1488. kind="clarification",
  1489. response={"response": response},
  1490. )
  1491. if replay is not None:
  1492. return replay
  1493. state, interaction = await self._interaction_runtime(
  1494. room_id, interaction_id, "clarification"
  1495. )
  1496. task = asyncio.create_task(
  1497. self._respond_clarification_for_runtime(
  1498. state=state,
  1499. interaction=interaction,
  1500. room_id=room_id,
  1501. interaction_id=interaction_id,
  1502. request_id=request_id,
  1503. response=response,
  1504. ),
  1505. name=f"yaoyao-group-clarification-{request_id}",
  1506. )
  1507. self._track_mutation_task(state, task)
  1508. return await asyncio.shield(task)
  1509. @staticmethod
  1510. def _track_mutation_task(
  1511. state: _RuntimeState, task: asyncio.Task[dict[str, object]]
  1512. ) -> None:
  1513. state.mutation_tasks.add(task)
  1514. def finished(done: asyncio.Task[dict[str, object]]) -> None:
  1515. state.mutation_tasks.discard(done)
  1516. if done.cancelled():
  1517. return
  1518. try:
  1519. done.exception()
  1520. except asyncio.CancelledError:
  1521. return
  1522. task.add_done_callback(finished)
  1523. async def _respond_clarification_for_runtime(
  1524. self,
  1525. *,
  1526. state: _RuntimeState,
  1527. interaction: Mapping[str, object],
  1528. room_id: str,
  1529. interaction_id: str,
  1530. request_id: str,
  1531. response: str,
  1532. ) -> dict[str, object]:
  1533. async with state.mutation_lock:
  1534. self._require_current_runtime(state)
  1535. claim = await self._run_state_blocking(
  1536. state,
  1537. self.store.begin_interaction_response,
  1538. room_id,
  1539. interaction_id,
  1540. request_id=request_id,
  1541. kind="clarification",
  1542. response={"response": response},
  1543. )
  1544. if not isinstance(claim, Mapping):
  1545. raise GroupOrchestratorError("Clarification claim is invalid")
  1546. if claim.get("state") in {"replay", "failed"}:
  1547. replay = claim.get("response")
  1548. return dict(replay) if isinstance(replay, Mapping) else dict(claim)
  1549. payload = interaction.get("payload")
  1550. gateway_request_id = (
  1551. payload.get("gatewayRequestId")
  1552. if isinstance(payload, Mapping)
  1553. else None
  1554. )
  1555. gateway_request_id = _required_string(
  1556. gateway_request_id, "interaction.payload.gatewayRequestId"
  1557. )
  1558. try:
  1559. status = await self._run_state_blocking(
  1560. state,
  1561. self._required_gateway().respond_clarification,
  1562. gateway_request_id,
  1563. response,
  1564. )
  1565. except Exception:
  1566. await self._fail_unknown_interaction_response_locked(
  1567. state, request_id, "Gateway clarification outcome is unknown"
  1568. )
  1569. raise GroupOrchestratorError("Gateway clarification outcome is unknown")
  1570. if status not in {"ok", "expired"}:
  1571. await self._fail_unknown_interaction_response_locked(
  1572. state, request_id, "Gateway clarification result is invalid"
  1573. )
  1574. raise GroupOrchestratorError("Gateway clarification result is invalid")
  1575. public = {
  1576. "accepted": status == "ok",
  1577. "interactionId": interaction_id,
  1578. }
  1579. try:
  1580. result = await self._store_retry(
  1581. state,
  1582. self.store.finish_interaction_response,
  1583. request_id,
  1584. response=public,
  1585. interaction_status=("resolved" if status == "ok" else "cancelled"),
  1586. )
  1587. except Exception:
  1588. await self._finalize_state_locked(
  1589. state,
  1590. outcome="failed",
  1591. error="Durable clarification response could not be completed",
  1592. interrupt=True,
  1593. )
  1594. raise
  1595. state.pending_interaction_ids.discard(interaction_id)
  1596. return dict(result)
  1597. async def _terminal_interaction_replay(
  1598. self,
  1599. *,
  1600. room_id: str,
  1601. interaction_id: str,
  1602. request_id: str,
  1603. kind: str,
  1604. response: Mapping[str, object],
  1605. ) -> dict[str, object] | None:
  1606. interaction = await asyncio.to_thread(
  1607. self.store.get_interaction, interaction_id
  1608. )
  1609. if (
  1610. not isinstance(interaction, Mapping)
  1611. or interaction.get("roomId") != room_id
  1612. or interaction.get("kind") != kind
  1613. ):
  1614. raise GroupOrchestratorError("Interaction is not in this room")
  1615. if interaction.get("status") == "pending":
  1616. return None
  1617. result = await asyncio.to_thread(
  1618. self.store.begin_interaction_response,
  1619. room_id,
  1620. interaction_id,
  1621. request_id=request_id,
  1622. kind=kind,
  1623. response=response,
  1624. )
  1625. if not isinstance(result, Mapping):
  1626. raise GroupOrchestratorError("Interaction replay is invalid")
  1627. replay = result.get("response")
  1628. if result.get("state") == "replay" and isinstance(replay, Mapping):
  1629. return dict(replay)
  1630. if result.get("state") == "failed":
  1631. return dict(result)
  1632. raise GroupOrchestratorError("Interaction is already terminal")
  1633. async def _interaction_runtime(
  1634. self, room_id: str, interaction_id: str, kind: str
  1635. ) -> tuple[_RuntimeState, Mapping[str, object]]:
  1636. interaction = await asyncio.to_thread(
  1637. self.store.get_interaction, interaction_id
  1638. )
  1639. if (
  1640. not isinstance(interaction, Mapping)
  1641. or interaction.get("roomId") != room_id
  1642. or interaction.get("kind") != kind
  1643. or interaction.get("status") != "pending"
  1644. ):
  1645. raise GroupOrchestratorError("Interaction is not pending in this room")
  1646. run_id = _required_string(interaction.get("runId"), "interaction.runId")
  1647. run = await asyncio.to_thread(self.store.get_run, run_id)
  1648. runtime_id = _required_string(
  1649. run.get("runtimeSessionId") if isinstance(run, Mapping) else None,
  1650. "run.runtimeSessionId",
  1651. )
  1652. with self._mapping_lock:
  1653. current = self._runtime_states.get(runtime_id)
  1654. if current is None or current[1].run_id != run_id:
  1655. raise GroupOrchestratorError("Interaction runtime is not active")
  1656. return current[1], interaction
  1657. def _require_current_runtime(self, state: _RuntimeState) -> None:
  1658. with self._mapping_lock:
  1659. current = self._runtime_states.get(state.runtime_id)
  1660. if (
  1661. current != (state.generation, state)
  1662. or state.finished.is_set()
  1663. or state.finalizing
  1664. ):
  1665. raise GroupOrchestratorError("Interaction runtime generation changed")
  1666. async def _fail_unknown_interaction_response_locked(
  1667. self, state: _RuntimeState, request_id: str, reason: str
  1668. ) -> None:
  1669. try:
  1670. await self._store_retry(
  1671. state,
  1672. self.store.fail_interaction_response,
  1673. request_id,
  1674. reason=reason,
  1675. uncertain=True,
  1676. )
  1677. except Exception:
  1678. logger.error("Failed to persist unknown interaction outcome")
  1679. await self._finalize_state_locked(
  1680. state, outcome="failed", error=reason, interrupt=True
  1681. )
  1682. async def shutdown(self) -> None:
  1683. """Stop claims, settle every owned runtime, drain, then close Gateway."""
  1684. if self._lifecycle_lock is None:
  1685. self._lifecycle_lock = asyncio.Lock()
  1686. wait_for_owner: asyncio.Event | None = None
  1687. completed_shutdown = False
  1688. async with self._lifecycle_lock:
  1689. if not self._started:
  1690. self._closing = True
  1691. completed_shutdown = bool(
  1692. self._shutdown_complete is not None
  1693. and self._shutdown_complete.is_set()
  1694. )
  1695. if not completed_shutdown:
  1696. return
  1697. scheduler = None
  1698. elif self._closing:
  1699. wait_for_owner = self._shutdown_complete
  1700. scheduler = None
  1701. else:
  1702. self._closing = True
  1703. if self._shutdown_event is not None:
  1704. self._shutdown_event.set()
  1705. if self._wake_event is not None:
  1706. self._wake_event.set()
  1707. scheduler = self._scheduler_task
  1708. if completed_shutdown:
  1709. if self._shutdown_error is not None:
  1710. raise self._shutdown_error
  1711. return
  1712. if wait_for_owner is not None:
  1713. await wait_for_owner.wait()
  1714. if self._shutdown_error is not None:
  1715. raise self._shutdown_error
  1716. return
  1717. first_error: BaseException | None = None
  1718. def remember(error: BaseException) -> None:
  1719. nonlocal first_error
  1720. if first_error is None:
  1721. first_error = error
  1722. if scheduler is not None:
  1723. try:
  1724. await scheduler
  1725. except BaseException as error: # noqa: BLE001 - cleanup continues
  1726. remember(error)
  1727. while self._run_tasks:
  1728. tasks = tuple(self._run_tasks)
  1729. try:
  1730. results = await asyncio.gather(*tasks, return_exceptions=True)
  1731. except BaseException as error: # noqa: BLE001 - cleanup continues
  1732. remember(error)
  1733. else:
  1734. self._remember_task_results(results, remember)
  1735. while self._control_tasks:
  1736. tasks = tuple(self._control_tasks)
  1737. try:
  1738. results = await asyncio.gather(*tasks, return_exceptions=True)
  1739. except BaseException as error: # noqa: BLE001 - cleanup continues
  1740. remember(error)
  1741. else:
  1742. self._remember_task_results(results, remember)
  1743. with self._failure_lock:
  1744. run_failures = tuple(self._run_failures)
  1745. durable_failures = tuple(self._durable_failures)
  1746. for error in (*run_failures, *durable_failures):
  1747. remember(error)
  1748. with self._mapping_lock:
  1749. remaining_states = [
  1750. state for _generation, state in self._runtime_states.values()
  1751. ]
  1752. for state in remaining_states:
  1753. if state.settle_error is not None:
  1754. remember(state.settle_error)
  1755. current_task = asyncio.current_task()
  1756. for helper in (state.event_task, state.grace_task):
  1757. if helper is None or helper is current_task:
  1758. continue
  1759. if not helper.done():
  1760. helper.cancel()
  1761. try:
  1762. results = await asyncio.gather(helper, return_exceptions=True)
  1763. except BaseException as error: # noqa: BLE001 - cleanup continues
  1764. remember(error)
  1765. else:
  1766. self._remember_task_results(results, remember)
  1767. pending_calls = tuple(state.inflight_calls)
  1768. if pending_calls:
  1769. try:
  1770. results = await asyncio.gather(
  1771. *pending_calls, return_exceptions=True
  1772. )
  1773. except BaseException as error: # noqa: BLE001 - cleanup continues
  1774. remember(error)
  1775. else:
  1776. self._remember_task_results(results, remember)
  1777. self._remove_runtime(state)
  1778. try:
  1779. await asyncio.to_thread(
  1780. self._required_gateway().close, state.runtime_id
  1781. )
  1782. except BaseException as error: # noqa: BLE001 - cleanup continues
  1783. remember(error)
  1784. state.finished.set()
  1785. gateway = self._gateway
  1786. if gateway is not None:
  1787. drain: Callable[[float | None], object] | None = None
  1788. try:
  1789. transport = getattr(gateway, "transport", None)
  1790. candidate = getattr(transport, "drain", None)
  1791. if callable(candidate):
  1792. drain = candidate
  1793. except BaseException as error: # noqa: BLE001 - shutdown still runs
  1794. remember(error)
  1795. if drain is not None:
  1796. try:
  1797. await asyncio.to_thread(drain, None)
  1798. except BaseException as error: # noqa: BLE001 - cleanup continues
  1799. remember(error)
  1800. try:
  1801. await asyncio.to_thread(gateway.shutdown)
  1802. except BaseException as error: # noqa: BLE001 - cleanup continues
  1803. remember(error)
  1804. try:
  1805. event_queue = self._event_queue
  1806. event_task = self._event_task
  1807. if event_queue is not None:
  1808. try:
  1809. await event_queue.join()
  1810. await event_queue.put(None)
  1811. except BaseException as error: # noqa: BLE001 - completion must signal
  1812. remember(error)
  1813. if event_task is not None:
  1814. try:
  1815. await event_task
  1816. except BaseException as error: # noqa: BLE001 - completion must signal
  1817. remember(error)
  1818. finally:
  1819. async with self._lifecycle_lock:
  1820. self._started = False
  1821. self._gateway = None
  1822. self._scheduler_task = None
  1823. self._event_task = None
  1824. self._shutdown_error = first_error
  1825. if self._shutdown_complete is not None:
  1826. self._shutdown_complete.set()
  1827. if first_error is not None:
  1828. raise first_error
  1829. @staticmethod
  1830. def _remember_task_results(
  1831. results: list[object], remember: Callable[[BaseException], None]
  1832. ) -> None:
  1833. for result in results:
  1834. if isinstance(result, BaseException) and not isinstance(
  1835. result, asyncio.CancelledError
  1836. ):
  1837. remember(result)
  1838. async def _scheduler(self) -> None:
  1839. wake_event = self._wake_event
  1840. shutdown_event = self._shutdown_event
  1841. if wake_event is None or shutdown_event is None:
  1842. raise GroupOrchestratorError("Scheduler started without lifecycle state")
  1843. claim_failure_count = 0
  1844. while True:
  1845. await wake_event.wait()
  1846. wake_event.clear()
  1847. if shutdown_event.is_set():
  1848. return
  1849. self._scheduler_busy = True
  1850. try:
  1851. if not await self._work_is_enabled():
  1852. if await self._wait_for_disabled_work(shutdown_event, wake_event):
  1853. return
  1854. continue
  1855. try:
  1856. more_cascades = await self._drain_pending_cascades()
  1857. except Exception: # noqa: BLE001 - durable ledger remains pending
  1858. claim_failure_count += 1
  1859. delay = min(
  1860. _STORE_RETRY_DELAYS[0]
  1861. * (2 ** min(claim_failure_count - 1, 10)),
  1862. _CLAIM_RETRY_MAX_SECONDS,
  1863. )
  1864. logger.error("Pending YaoYao group cascade temporarily failed")
  1865. try:
  1866. await asyncio.wait_for(shutdown_event.wait(), timeout=delay)
  1867. except asyncio.TimeoutError:
  1868. wake_event.set()
  1869. continue
  1870. return
  1871. if more_cascades:
  1872. wake_event.set()
  1873. continue
  1874. while not shutdown_event.is_set():
  1875. if not await self._work_is_enabled():
  1876. if await self._wait_for_disabled_work(
  1877. shutdown_event, wake_event
  1878. ):
  1879. return
  1880. break
  1881. try:
  1882. claimed = await asyncio.to_thread(
  1883. self.store.claim_next_runnable_run
  1884. )
  1885. except Exception: # noqa: BLE001 - keep scheduler alive
  1886. claim_failure_count += 1
  1887. delay = min(
  1888. _STORE_RETRY_DELAYS[0]
  1889. * (2 ** min(claim_failure_count - 1, 10)),
  1890. _CLAIM_RETRY_MAX_SECONDS,
  1891. )
  1892. logger.error("YaoYao group run claim temporarily failed")
  1893. try:
  1894. await asyncio.wait_for(shutdown_event.wait(), timeout=delay)
  1895. except asyncio.TimeoutError:
  1896. continue
  1897. return
  1898. claim_failure_count = 0
  1899. if claimed is None:
  1900. break
  1901. task = asyncio.create_task(
  1902. self._run_claimed(claimed),
  1903. name=f"yaoyao-group-run-{claimed.get('id', 'invalid')}",
  1904. )
  1905. self._run_tasks.add(task)
  1906. task.add_done_callback(self._run_finished)
  1907. finally:
  1908. self._scheduler_busy = False
  1909. async def _work_is_enabled(self) -> bool:
  1910. try:
  1911. return await asyncio.to_thread(self._work_enabled) is True
  1912. except Exception as error: # noqa: BLE001 - fail closed on config errors
  1913. _log_failure_type("YaoYao group work gate temporarily failed", error)
  1914. return False
  1915. @staticmethod
  1916. async def _wait_for_disabled_work(
  1917. shutdown_event: asyncio.Event,
  1918. wake_event: asyncio.Event,
  1919. ) -> bool:
  1920. try:
  1921. await asyncio.wait_for(
  1922. shutdown_event.wait(), timeout=_WORK_DISABLED_RETRY_SECONDS
  1923. )
  1924. except asyncio.TimeoutError:
  1925. wake_event.set()
  1926. return False
  1927. return True
  1928. async def _drain_pending_cascades(self) -> bool:
  1929. page = await asyncio.to_thread(self.store.list_pending_cascades, limit=32)
  1930. if not isinstance(page, Mapping):
  1931. raise GroupOrchestratorError("Pending cascade page is invalid")
  1932. items = page.get("items")
  1933. if not isinstance(items, list) or not all(
  1934. isinstance(item, Mapping) for item in items
  1935. ):
  1936. raise GroupOrchestratorError("Pending cascade items are invalid")
  1937. created = False
  1938. for item in items:
  1939. source_run_id = _required_string(
  1940. item.get("sourceRunId"), "cascade.sourceRunId"
  1941. )
  1942. result = await asyncio.to_thread(self.store.complete_cascade, source_run_id)
  1943. if not isinstance(result, Mapping):
  1944. raise GroupOrchestratorError("Cascade completion is invalid")
  1945. run_count = result.get("runCount")
  1946. if isinstance(run_count, bool) or not isinstance(run_count, int):
  1947. raise GroupOrchestratorError("Cascade run count is invalid")
  1948. created = created or run_count > 0
  1949. if created:
  1950. self.wake()
  1951. return page.get("nextCursor") is not None
  1952. def _run_finished(self, task: asyncio.Task[None]) -> None:
  1953. self._run_tasks.discard(task)
  1954. try:
  1955. error = task.exception()
  1956. except asyncio.CancelledError:
  1957. error = None
  1958. if error is not None:
  1959. with self._failure_lock:
  1960. self._run_failures.append(error)
  1961. _log_failure_type("YaoYao group run task failed", error)
  1962. self.wake()
  1963. async def _run_claimed(self, claimed: Mapping[str, object]) -> None:
  1964. run_id_value = claimed.get("id")
  1965. if not isinstance(run_id_value, str) or not run_id_value:
  1966. logger.error("Claimed YaoYao group run has no usable identity")
  1967. return
  1968. run_id = run_id_value
  1969. try:
  1970. claimed_agent_id = _required_string(claimed.get("agentId"), "run.agentId")
  1971. async with self._agent_serial(claimed_agent_id):
  1972. try:
  1973. await self._run_claimed_for_agent(claimed, run_id)
  1974. except Exception: # noqa: BLE001 - never strand a durable claim
  1975. logger.exception("YaoYao group claimed run preparation failed")
  1976. await self._fail_claim_without_projection(run_id)
  1977. except Exception: # noqa: BLE001 - malformed claim still has run ID
  1978. logger.exception("YaoYao group claimed run identity is invalid")
  1979. await self._fail_claim_without_projection(run_id)
  1980. @asynccontextmanager
  1981. async def _agent_serial(self, agent_id: str):
  1982. async with self._keyed_serial(self._agent_locks, agent_id):
  1983. yield
  1984. @asynccontextmanager
  1985. async def _submission_serial(self, agent_id: str):
  1986. async with self._keyed_serial(self._submission_locks, agent_id):
  1987. yield
  1988. @asynccontextmanager
  1989. async def _room_serial(self, room_id: str):
  1990. async with self._keyed_serial(self._room_locks, room_id):
  1991. yield
  1992. @staticmethod
  1993. @asynccontextmanager
  1994. async def _keyed_serial(locks: dict[str, _AgentLockState], key: str):
  1995. entry = locks.get(key)
  1996. if entry is None:
  1997. entry = _AgentLockState()
  1998. locks[key] = entry
  1999. entry.users += 1
  2000. try:
  2001. async with entry.lock:
  2002. yield
  2003. finally:
  2004. entry.users -= 1
  2005. if entry.users == 0 and locks.get(key) is entry:
  2006. locks.pop(key, None)
  2007. async def _run_claimed_for_agent(
  2008. self, claimed: Mapping[str, object], run_id: str
  2009. ) -> None:
  2010. try:
  2011. projection = await asyncio.to_thread(self.store.read_run_projection, run_id)
  2012. except Exception: # noqa: BLE001 - durable claim must be terminal
  2013. logger.exception("Failed to read YaoYao group run projection")
  2014. await self._fail_claim_without_projection(run_id)
  2015. return
  2016. run = _required_mapping(projection.get("run"), "projection.run")
  2017. room = _required_mapping(projection.get("room"), "projection.room")
  2018. agent = _required_mapping(projection.get("agent"), "projection.agent")
  2019. room_id = _required_string(room.get("id"), "projection.room.id")
  2020. topic_id = _required_string(run.get("topicId"), "projection.run.topicId")
  2021. agent_id = _required_string(agent.get("id"), "projection.agent.id")
  2022. if _required_string(run.get("id"), "projection.run.id") != run_id:
  2023. raise GroupOrchestratorError("projection run identity changed")
  2024. if agent_id != _required_string(claimed.get("agentId"), "run.agentId"):
  2025. raise GroupOrchestratorError("projection Agent identity changed")
  2026. configuration = {
  2027. "model": agent.get("model"),
  2028. "provider": agent.get("provider"),
  2029. "reasoning_effort": agent.get("reasoningEffort"),
  2030. "fast": agent.get("fastMode"),
  2031. }
  2032. try:
  2033. rotated = await asyncio.to_thread(
  2034. self.store.prepare_run_session_configuration,
  2035. run_id,
  2036. configuration,
  2037. )
  2038. if rotated:
  2039. projection = await asyncio.to_thread(
  2040. self.store.read_run_projection, run_id
  2041. )
  2042. run = _required_mapping(projection.get("run"), "projection.run")
  2043. room = _required_mapping(projection.get("room"), "projection.room")
  2044. agent = _required_mapping(projection.get("agent"), "projection.agent")
  2045. except Exception:
  2046. logger.exception("Failed to prepare YaoYao group Agent configuration")
  2047. await self._fail_claim_without_projection(run_id)
  2048. return
  2049. profile = _required_string(agent.get("profile"), "projection.agent.profile")
  2050. node_id = _required_string(
  2051. agent.get("nodeId", "local"), "projection.agent.nodeId"
  2052. )
  2053. reply_mode = _required_string(run.get("replyMode"), "projection.run.replyMode")
  2054. if reply_mode not in {"mentioned", "automatic"}:
  2055. raise GroupOrchestratorError("projection.run.replyMode is invalid")
  2056. required_reply = _required_bool(
  2057. run.get("requiredReply", False), "projection.run.requiredReply"
  2058. )
  2059. if required_reply and reply_mode != "automatic":
  2060. raise GroupOrchestratorError(
  2061. "projection.run.requiredReply requires automatic replyMode"
  2062. )
  2063. display_name = _required_string(
  2064. agent.get("displayName"), "projection.agent.displayName"
  2065. )
  2066. room_name = _required_string(room.get("name"), "projection.room.name")
  2067. cwd_value = room.get("cwd", "")
  2068. if not isinstance(cwd_value, str):
  2069. raise GroupOrchestratorError("projection.room.cwd must be a string")
  2070. expected_stored_id = _optional_string(
  2071. agent.get("storedSessionId"), "projection.agent.storedSessionId"
  2072. )
  2073. expected_context_seq = _required_nonnegative_int(
  2074. agent.get("lastContextMessageSeq"),
  2075. "projection.agent.lastContextMessageSeq",
  2076. )
  2077. through_seq = _required_nonnegative_int(
  2078. projection.get("throughSeq"), "projection.throughSeq"
  2079. )
  2080. room_detail = await asyncio.to_thread(self.store.get_room, room_id)
  2081. room_agents = room_detail.get("agents")
  2082. if not isinstance(room_agents, list) or not all(
  2083. isinstance(item, Mapping) for item in room_agents
  2084. ):
  2085. raise GroupOrchestratorError("room.agents must be a list of objects")
  2086. prompt = build_run_prompt(projection, room_agents)
  2087. gateway = self._required_gateway()
  2088. try:
  2089. if expected_stored_id is None:
  2090. if node_id == "local":
  2091. identity = await asyncio.to_thread(
  2092. gateway.create_session,
  2093. profile,
  2094. f"[群聊] {room_name} · {display_name}",
  2095. cwd_value,
  2096. [],
  2097. configuration,
  2098. )
  2099. else:
  2100. create_remote = getattr(
  2101. gateway, "create_session_for_node", None
  2102. )
  2103. if not callable(create_remote):
  2104. raise GroupOrchestratorError(
  2105. "Gateway does not support remote nodes"
  2106. )
  2107. identity = await asyncio.to_thread(
  2108. create_remote,
  2109. node_id,
  2110. profile,
  2111. f"[群聊] {room_name} · {display_name}",
  2112. "",
  2113. [],
  2114. configuration,
  2115. )
  2116. else:
  2117. if node_id == "local":
  2118. identity = await asyncio.to_thread(
  2119. gateway.resume_session, profile, expected_stored_id
  2120. )
  2121. else:
  2122. resume_remote = getattr(
  2123. gateway, "resume_session_for_node", None
  2124. )
  2125. if not callable(resume_remote):
  2126. raise GroupOrchestratorError(
  2127. "Gateway does not support remote nodes"
  2128. )
  2129. identity = await asyncio.to_thread(
  2130. resume_remote,
  2131. node_id,
  2132. profile,
  2133. expected_stored_id,
  2134. )
  2135. except Exception: # noqa: BLE001 - never create a fallback session
  2136. logger.error("YaoYao group session create/resume failed")
  2137. await self._settle_unbound_failed(
  2138. run_id,
  2139. expected_stored_id=expected_stored_id,
  2140. stored_session_id=expected_stored_id,
  2141. error="Agent session setup failed",
  2142. )
  2143. return
  2144. identity = self._validated_identity(identity)
  2145. if identity.running:
  2146. # A busy resume may belong to another consumer. Persist rotation,
  2147. # but never adopt, submit to, interrupt, or close that runtime.
  2148. await self._settle_unbound_failed(
  2149. run_id,
  2150. expected_stored_id=expected_stored_id,
  2151. stored_session_id=identity.stored_id,
  2152. error="Agent stored session is already running",
  2153. )
  2154. return
  2155. bound = False
  2156. for delay in (*_STORE_RETRY_DELAYS, None):
  2157. try:
  2158. await asyncio.to_thread(
  2159. self.store.bind_run_runtime, run_id, identity.runtime_id
  2160. )
  2161. bound = True
  2162. break
  2163. except Exception: # noqa: BLE001 - exact bind replay is idempotent
  2164. if delay is None:
  2165. try:
  2166. durable = await asyncio.to_thread(self.store.get_run, run_id)
  2167. except Exception: # noqa: BLE001 - identity remains unknown
  2168. durable = None
  2169. bound = (
  2170. isinstance(durable, Mapping)
  2171. and durable.get("status") in {"running", "awaiting_input"}
  2172. and durable.get("runtimeSessionId") == identity.runtime_id
  2173. )
  2174. break
  2175. await asyncio.sleep(delay)
  2176. if not bound:
  2177. logger.error("Failed to bind YaoYao group runtime")
  2178. await self._close_unbound_runtime(identity.runtime_id)
  2179. await self._settle_unbound_failed(
  2180. run_id,
  2181. expected_stored_id=expected_stored_id,
  2182. stored_session_id=identity.stored_id,
  2183. error="Agent runtime binding failed",
  2184. )
  2185. return
  2186. async with self._room_serial(room_id):
  2187. async with self._submission_serial(agent_id):
  2188. durable = None
  2189. for delay in (*_STORE_RETRY_DELAYS, None):
  2190. try:
  2191. durable = await asyncio.to_thread(self.store.get_run, run_id)
  2192. break
  2193. except Exception: # noqa: BLE001 - unknown owner cannot submit
  2194. if delay is None:
  2195. break
  2196. await asyncio.sleep(delay)
  2197. if (
  2198. not isinstance(durable, Mapping)
  2199. or durable.get("status") not in {"running", "awaiting_input"}
  2200. or durable.get("runtimeSessionId") != identity.runtime_id
  2201. ):
  2202. logger.error("Bound YaoYao group runtime lost durable ownership")
  2203. await self._close_unbound_runtime(identity.runtime_id)
  2204. if not (
  2205. isinstance(durable, Mapping)
  2206. and durable.get("status") in _TERMINAL_RUN_STATUSES
  2207. ):
  2208. await self._settle_unbound_failed(
  2209. run_id,
  2210. expected_stored_id=expected_stored_id,
  2211. stored_session_id=identity.stored_id,
  2212. error="Agent runtime ownership check failed",
  2213. )
  2214. return
  2215. state = self._install_runtime(
  2216. run_id=run_id,
  2217. room_id=room_id,
  2218. topic_id=topic_id,
  2219. agent_id=agent_id,
  2220. identity=identity,
  2221. expected_stored_id=expected_stored_id,
  2222. expected_context_seq=expected_context_seq,
  2223. through_seq=through_seq,
  2224. profile=profile,
  2225. reply_mode=reply_mode,
  2226. required_reply=required_reply,
  2227. )
  2228. if self._closing:
  2229. state.prompt_ready.set()
  2230. await self._finalize_state(
  2231. state,
  2232. outcome="interrupted",
  2233. error="Group orchestrator stopped",
  2234. interrupt=True,
  2235. )
  2236. return
  2237. try:
  2238. await self._run_state_blocking(
  2239. state, gateway.submit_prompt, identity.runtime_id, prompt
  2240. )
  2241. except Exception: # noqa: BLE001 - ACK is intentionally unknown
  2242. logger.error("YaoYao group prompt submission failed")
  2243. state.prompt_ready.set()
  2244. await self._finalize_state(
  2245. state,
  2246. outcome="failed",
  2247. error="Prompt submission result is unknown",
  2248. interrupt=True,
  2249. )
  2250. return
  2251. try:
  2252. for delay in (*_STORE_RETRY_DELAYS, None):
  2253. try:
  2254. await self._run_state_blocking(
  2255. state,
  2256. self.store.commit_prompt_submission,
  2257. run_id,
  2258. expected_stored_session_id=expected_stored_id,
  2259. stored_session_id=identity.stored_id,
  2260. runtime_session_id=identity.runtime_id,
  2261. expected_context_seq=expected_context_seq,
  2262. through_seq=through_seq,
  2263. )
  2264. state.prompt_committed = True
  2265. break
  2266. except Exception:
  2267. if delay is None:
  2268. raise
  2269. await asyncio.sleep(delay)
  2270. except Exception: # noqa: BLE001 - prompts are never retried
  2271. logger.error("Failed to commit YaoYao group prompt ACK")
  2272. state.prompt_ready.set()
  2273. await self._finalize_state(
  2274. state,
  2275. outcome="failed",
  2276. error="Prompt acknowledgement could not be committed",
  2277. interrupt=True,
  2278. )
  2279. return
  2280. finally:
  2281. state.prompt_ready.set()
  2282. if state.overflowed:
  2283. await self._finalize_state(
  2284. state,
  2285. outcome="failed",
  2286. error="Runtime control event buffer exceeded capacity",
  2287. interrupt=True,
  2288. )
  2289. return
  2290. shutdown_event = self._shutdown_event
  2291. if shutdown_event is None:
  2292. raise GroupOrchestratorError("Run started without shutdown state")
  2293. finished_wait = asyncio.create_task(state.finished.wait())
  2294. shutdown_wait = asyncio.create_task(shutdown_event.wait())
  2295. try:
  2296. done, pending = await asyncio.wait(
  2297. {finished_wait, shutdown_wait},
  2298. return_when=asyncio.FIRST_COMPLETED,
  2299. )
  2300. for waiter in pending:
  2301. waiter.cancel()
  2302. if finished_wait in done and state.finished.is_set():
  2303. return
  2304. if shutdown_wait in done and shutdown_event.is_set():
  2305. outcome = "interrupted"
  2306. error = "Group orchestrator stopped"
  2307. await self._finalize_state(
  2308. state, outcome=outcome, error=error, interrupt=True
  2309. )
  2310. finally:
  2311. for waiter in (finished_wait, shutdown_wait):
  2312. if not waiter.done():
  2313. waiter.cancel()
  2314. async def _fail_claim_without_projection(self, run_id: str) -> None:
  2315. for delay in (*_STORE_RETRY_DELAYS, None):
  2316. try:
  2317. await asyncio.to_thread(
  2318. self.store.transition_run,
  2319. run_id,
  2320. "failed",
  2321. error="Agent context projection failed",
  2322. )
  2323. return
  2324. except Exception: # noqa: BLE001 - reconcile before retrying
  2325. if await self._run_is_durably_terminal(run_id):
  2326. return
  2327. if delay is None:
  2328. logger.exception("Failed to settle malformed YaoYao group claim")
  2329. self._record_durable_failure(
  2330. "Durable claimed run settlement failed"
  2331. )
  2332. return
  2333. await asyncio.sleep(delay)
  2334. async def _settle_unbound_failed(
  2335. self,
  2336. run_id: str,
  2337. *,
  2338. expected_stored_id: str | None,
  2339. stored_session_id: str | None,
  2340. error: str,
  2341. ) -> None:
  2342. for delay in (*_STORE_RETRY_DELAYS, None):
  2343. try:
  2344. await asyncio.to_thread(
  2345. self.store.settle_run,
  2346. run_id,
  2347. runtime_session_id=None,
  2348. expected_stored_session_id=expected_stored_id,
  2349. stored_session_id=stored_session_id,
  2350. outcome="failed",
  2351. error=self._bounded_error(error),
  2352. )
  2353. return
  2354. except Exception: # noqa: BLE001 - reconcile before retrying
  2355. if await self._run_is_durably_terminal(run_id):
  2356. return
  2357. if delay is None:
  2358. logger.exception("Failed to settle unbound YaoYao group run")
  2359. self._record_durable_failure(
  2360. "Durable unbound run settlement failed"
  2361. )
  2362. return
  2363. await asyncio.sleep(delay)
  2364. def _record_durable_failure(self, message: str) -> None:
  2365. failure = GroupOrchestratorError(message)
  2366. with self._failure_lock:
  2367. self._durable_failures.append(failure)
  2368. async def _run_is_durably_terminal(self, run_id: str) -> bool:
  2369. try:
  2370. durable = await asyncio.to_thread(self.store.get_run, run_id)
  2371. except Exception: # noqa: BLE001 - missing is safe only for local cleanup
  2372. return False
  2373. return (
  2374. isinstance(durable, Mapping)
  2375. and durable.get("status") in _TERMINAL_RUN_STATUSES
  2376. )
  2377. async def _close_unbound_runtime(self, runtime_id: str) -> None:
  2378. try:
  2379. await asyncio.to_thread(self._required_gateway().close, runtime_id)
  2380. except Exception: # noqa: BLE001 - best effort after failed durable bind
  2381. logger.exception("Failed to close unbound YaoYao group runtime")
  2382. @staticmethod
  2383. def _validated_identity(identity: object) -> SessionIdentity:
  2384. stored_id = _required_string(
  2385. getattr(identity, "stored_id", None), "session.stored_id"
  2386. )
  2387. runtime_id = _required_string(
  2388. getattr(identity, "runtime_id", None), "session.runtime_id"
  2389. )
  2390. running = getattr(identity, "running", None)
  2391. if not isinstance(running, bool):
  2392. raise GroupOrchestratorError("session.running must be a boolean")
  2393. return SessionIdentity(stored_id, runtime_id, running)
  2394. def _install_runtime(
  2395. self,
  2396. *,
  2397. run_id: str,
  2398. room_id: str,
  2399. topic_id: str,
  2400. agent_id: str,
  2401. identity: SessionIdentity,
  2402. expected_stored_id: str | None,
  2403. expected_context_seq: int,
  2404. through_seq: int,
  2405. profile: str,
  2406. reply_mode: str,
  2407. required_reply: bool,
  2408. ) -> _RuntimeState:
  2409. with self._mapping_lock:
  2410. if identity.runtime_id in self._runtime_states:
  2411. raise GroupOrchestratorError(
  2412. "Gateway runtime is already mapped to an active generation"
  2413. )
  2414. self._next_generation += 1
  2415. state = _RuntimeState(
  2416. run_id=run_id,
  2417. room_id=room_id,
  2418. topic_id=topic_id,
  2419. agent_id=agent_id,
  2420. runtime_id=identity.runtime_id,
  2421. generation=self._next_generation,
  2422. expected_stored_id=expected_stored_id,
  2423. session_stored_id=identity.stored_id,
  2424. expected_context_seq=expected_context_seq,
  2425. through_seq=through_seq,
  2426. profile=profile,
  2427. reply_mode=reply_mode,
  2428. required_reply=required_reply,
  2429. automatic_published=required_reply,
  2430. )
  2431. self._runtime_states[identity.runtime_id] = (
  2432. state.generation,
  2433. state,
  2434. )
  2435. state.event_task = asyncio.create_task(
  2436. self._consume_runtime_events(state),
  2437. name=f"yaoyao-group-runtime-{state.generation}",
  2438. )
  2439. return state
  2440. def _remove_runtime(self, state: _RuntimeState) -> None:
  2441. with self._mapping_lock:
  2442. current = self._runtime_states.get(state.runtime_id)
  2443. if current == (state.generation, state):
  2444. self._runtime_states.pop(state.runtime_id, None)
  2445. def _gateway_event_callback(
  2446. self,
  2447. runtime_id: str,
  2448. event_type: str,
  2449. payload: dict[str, object],
  2450. ) -> None:
  2451. """Bridge the Gateway callback thread into one bounded asyncio queue."""
  2452. if event_type not in _PERSISTED_EVENTS:
  2453. return
  2454. with self._mapping_lock:
  2455. current = self._runtime_states.get(runtime_id)
  2456. if current is None:
  2457. logger.debug("Ignored event for an unmapped group runtime")
  2458. return
  2459. generation, _state = current
  2460. loop = self._loop
  2461. queue = self._event_queue
  2462. if loop is None or queue is None or loop.is_closed():
  2463. return
  2464. try:
  2465. safe_payload = _strict_json_copy(payload, "gateway.payload")
  2466. except GroupOrchestratorError:
  2467. logger.warning("Ignored malformed group Gateway payload")
  2468. return
  2469. if not isinstance(safe_payload, dict):
  2470. return
  2471. envelope = _GatewayEvent(
  2472. runtime_id=runtime_id,
  2473. generation=generation,
  2474. event_type=event_type,
  2475. payload=safe_payload,
  2476. )
  2477. if threading.get_ident() == self._loop_thread_id:
  2478. # The production transport uses a dedicated worker. Supporting a
  2479. # loop-local test callback is still safe while the queue has room.
  2480. try:
  2481. queue.put_nowait(envelope)
  2482. except asyncio.QueueFull:
  2483. logger.error("Loop-local group Gateway callback exceeded capacity")
  2484. return
  2485. try:
  2486. future = asyncio.run_coroutine_threadsafe(queue.put(envelope), loop)
  2487. future.result()
  2488. except (RuntimeError, asyncio.CancelledError):
  2489. return
  2490. async def _consume_events(self) -> None:
  2491. queue = self._event_queue
  2492. if queue is None:
  2493. raise GroupOrchestratorError("Event consumer has no queue")
  2494. while True:
  2495. event = await queue.get()
  2496. try:
  2497. if event is None:
  2498. return
  2499. await self._handle_event(event)
  2500. except Exception: # noqa: BLE001 - isolate all Gateway callbacks
  2501. logger.exception("Failed to consume YaoYao group Gateway event")
  2502. finally:
  2503. queue.task_done()
  2504. async def _handle_event(self, event: _GatewayEvent) -> None:
  2505. if event.event_type not in _PERSISTED_EVENTS:
  2506. return
  2507. with self._mapping_lock:
  2508. current = self._runtime_states.get(event.runtime_id)
  2509. if current is None or current[0] != event.generation:
  2510. logger.debug("Ignored stale group Gateway generation")
  2511. return
  2512. state = current[1]
  2513. if state.finished.is_set() or state.finalizing:
  2514. return
  2515. try:
  2516. state.pending_events.put_nowait(event)
  2517. except asyncio.QueueFull:
  2518. # The transport already applies global backpressure. A per-runtime
  2519. # overflow is an invariant breach: fail that run without blocking
  2520. # unrelated sessions in the one global router.
  2521. state.overflowed = True
  2522. state.prompt_ready.set()
  2523. async def _consume_runtime_events(self, state: _RuntimeState) -> None:
  2524. """Serialize one runtime without head-of-line blocking other sessions."""
  2525. await state.prompt_ready.wait()
  2526. while not state.finished.is_set():
  2527. if state.finalizing:
  2528. return
  2529. if state.overflowed and state.prompt_committed:
  2530. await self._finalize_state(
  2531. state,
  2532. outcome="failed",
  2533. error="Runtime control event buffer exceeded capacity",
  2534. interrupt=True,
  2535. )
  2536. return
  2537. timeout: float | None = None
  2538. if state.stream_dirty and not (
  2539. state.reply_mode == "automatic" and not state.automatic_published
  2540. ):
  2541. timeout = max(
  2542. 0.0,
  2543. STREAM_FLUSH_INTERVAL
  2544. - (asyncio.get_running_loop().time() - state.last_stream_flush),
  2545. )
  2546. try:
  2547. if timeout is None:
  2548. event = await state.pending_events.get()
  2549. else:
  2550. event = await asyncio.wait_for(
  2551. state.pending_events.get(), timeout=timeout
  2552. )
  2553. except asyncio.TimeoutError:
  2554. async with state.mutation_lock:
  2555. if state.finished.is_set() or state.finalizing:
  2556. return
  2557. with self._mapping_lock:
  2558. current = self._runtime_states.get(state.runtime_id)
  2559. if current != (state.generation, state):
  2560. continue
  2561. try:
  2562. await self._flush_streaming(state)
  2563. except Exception: # noqa: BLE001 - fail this runtime durably
  2564. logger.error("Failed to persist YaoYao group streaming message")
  2565. await self._finalize_state_locked(
  2566. state,
  2567. outcome="failed",
  2568. error="Streaming Agent message could not be persisted",
  2569. interrupt=True,
  2570. )
  2571. continue
  2572. try:
  2573. if event is None:
  2574. return
  2575. if not state.prompt_committed:
  2576. continue
  2577. with self._mapping_lock:
  2578. current = self._runtime_states.get(event.runtime_id)
  2579. if current != (event.generation, state):
  2580. continue
  2581. state.event_index += 1
  2582. async with state.mutation_lock:
  2583. try:
  2584. await self._apply_runtime_event(state, event)
  2585. except Exception: # noqa: BLE001 - fail this runtime only
  2586. logger.error("Failed to process YaoYao group runtime event")
  2587. await self._finalize_state_locked(
  2588. state,
  2589. outcome="failed",
  2590. error="Gateway control event could not be persisted",
  2591. interrupt=True,
  2592. )
  2593. except Exception: # noqa: BLE001 - isolate this runtime only
  2594. logger.error("Failed to lock YaoYao group runtime event")
  2595. await self._finalize_state(
  2596. state,
  2597. outcome="failed",
  2598. error="Gateway control event could not be persisted",
  2599. interrupt=True,
  2600. )
  2601. finally:
  2602. state.pending_events.task_done()
  2603. async def _apply_runtime_event(
  2604. self, state: _RuntimeState, event: _GatewayEvent
  2605. ) -> None:
  2606. event_type = event.event_type
  2607. payload = event.payload
  2608. if state.finalizing:
  2609. return
  2610. self._require_safe_control_payload(event_type, payload)
  2611. if state.complete_seen and event_type != "session.info":
  2612. return
  2613. if event_type == "message.start":
  2614. if state.reply_mode == "mentioned" or state.automatic_published:
  2615. await self._persist_message_snapshot(state, status="streaming")
  2616. return
  2617. if event_type in {"message.delta", "reasoning.delta"}:
  2618. text = payload.get("text")
  2619. if not isinstance(text, str):
  2620. raise GroupOrchestratorError("Gateway delta text is invalid")
  2621. if event_type == "message.delta":
  2622. state.content = self._append_bounded_text(
  2623. state.content, text, "content"
  2624. )
  2625. else:
  2626. state.reasoning = self._append_bounded_text(
  2627. state.reasoning, text, "reasoning"
  2628. )
  2629. state.stream_dirty = True
  2630. now = asyncio.get_running_loop().time()
  2631. if state.last_stream_flush == 0.0 or (
  2632. now - state.last_stream_flush >= STREAM_FLUSH_INTERVAL
  2633. ):
  2634. await self._flush_streaming(state)
  2635. return
  2636. if event_type.startswith("tool."):
  2637. await self._publish_automatic_state(state)
  2638. await self._flush_streaming(state)
  2639. self._merge_tool_event(state, event_type, payload)
  2640. await self._persist_message_snapshot(state, status="streaming")
  2641. return
  2642. if event_type == "approval.request":
  2643. await self._publish_automatic_state(state)
  2644. await self._flush_streaming(state)
  2645. await self._persist_approval(state, payload)
  2646. return
  2647. if event_type == "clarify.request":
  2648. await self._publish_automatic_state(state)
  2649. await self._flush_streaming(state)
  2650. await self._persist_clarification(state, payload)
  2651. return
  2652. if event_type == "clarify.expire":
  2653. await self._publish_automatic_state(state)
  2654. await self._flush_streaming(state)
  2655. await self._expire_clarification(state, payload)
  2656. return
  2657. if event_type == "message.complete":
  2658. if state.complete_seen:
  2659. return
  2660. await self._flush_streaming(state)
  2661. await self._expire_pending_interactions(state)
  2662. status = payload.get("status")
  2663. outcomes = {
  2664. "complete": "completed",
  2665. "error": "failed",
  2666. "interrupted": "interrupted",
  2667. }
  2668. outcome = outcomes.get(status) if isinstance(status, str) else None
  2669. if outcome is None:
  2670. outcome = "failed"
  2671. state.terminal_error = "Invalid message.complete status"
  2672. else:
  2673. raw_error = payload.get("error")
  2674. if outcome != "completed" and isinstance(raw_error, str):
  2675. state.terminal_error = self._bounded_error(raw_error)
  2676. for tool in state.tool_state:
  2677. if tool.get("status") == "running":
  2678. tool["status"] = "completed" if outcome == "completed" else "failed"
  2679. final_text = payload.get("text", payload.get("content"))
  2680. if isinstance(final_text, str):
  2681. state.content = self._bounded_text(final_text, "content")
  2682. final_reasoning = payload.get("reasoning")
  2683. if isinstance(final_reasoning, str):
  2684. state.reasoning = self._bounded_text(final_reasoning, "reasoning")
  2685. automatic_unpublished = (
  2686. state.reply_mode == "automatic" and not state.automatic_published
  2687. )
  2688. if state.reply_mode == "automatic":
  2689. state.content = _sanitize_no_reply_text(state.content)
  2690. state.reasoning = _sanitize_no_reply_text(state.reasoning)
  2691. if (
  2692. state.required_reply
  2693. and outcome == "completed"
  2694. and not state.content.strip()
  2695. and not state.had_visible_interaction
  2696. ):
  2697. state.content = _HOST_FALLBACK_REPLY
  2698. suppress_automatic = automatic_unpublished and (
  2699. outcome != "completed" or not state.content.strip()
  2700. )
  2701. if suppress_automatic:
  2702. state.content = ""
  2703. state.reasoning = ""
  2704. state.tool_state = []
  2705. elif automatic_unpublished:
  2706. state.automatic_published = True
  2707. # GroupStore only accepts completed as a direct running-run
  2708. # terminal upsert. Failure/interruption must first persist the
  2709. # partial body as streaming; settle_run atomically maps both run
  2710. # and response message to the final failed/interrupted status.
  2711. message_status = "completed" if outcome == "completed" else "streaming"
  2712. try:
  2713. await self._persist_message_snapshot(
  2714. state,
  2715. status=message_status,
  2716. error=state.terminal_error,
  2717. publish=not suppress_automatic,
  2718. )
  2719. state.stream_dirty = False
  2720. except Exception:
  2721. await self._finalize_state_locked(
  2722. state,
  2723. outcome="failed",
  2724. error="Terminal Agent message could not be persisted",
  2725. interrupt=True,
  2726. )
  2727. return
  2728. state.terminal_status = outcome
  2729. state.complete_seen = True
  2730. state.complete_index = state.event_index
  2731. state.grace_task = asyncio.create_task(
  2732. self._await_terminal_info(state),
  2733. name=f"yaoyao-group-grace-{state.generation}",
  2734. )
  2735. return
  2736. if event_type == "session.info":
  2737. await self._flush_streaming(state)
  2738. if (
  2739. payload.get("running") is not False
  2740. or not state.complete_seen
  2741. or state.event_index <= state.complete_index
  2742. ):
  2743. return
  2744. profile_name = payload.get("profile_name")
  2745. if profile_name != state.profile:
  2746. await self._finalize_state_locked(
  2747. state,
  2748. outcome="failed",
  2749. error="Final session profile is missing",
  2750. stored_session_id=state.session_stored_id,
  2751. interrupt=True,
  2752. )
  2753. return
  2754. rotated = payload.get("stored_session_id")
  2755. if not isinstance(rotated, str) or not rotated:
  2756. await self._finalize_state_locked(
  2757. state,
  2758. outcome="failed",
  2759. error="Final session identity is missing",
  2760. stored_session_id=state.session_stored_id,
  2761. interrupt=True,
  2762. )
  2763. return
  2764. actual_model = payload.get("model")
  2765. actual_provider = payload.get("provider")
  2766. if (
  2767. isinstance(actual_model, str)
  2768. and actual_model.strip()
  2769. and isinstance(actual_provider, str)
  2770. and actual_provider.strip()
  2771. ):
  2772. state.actual_model = actual_model.strip()
  2773. state.actual_provider = actual_provider.strip()
  2774. actual_reasoning = payload.get("reasoning_effort")
  2775. if isinstance(actual_reasoning, str) and actual_reasoning.strip():
  2776. state.actual_reasoning_effort = actual_reasoning.strip()
  2777. actual_fast = payload.get("fast")
  2778. if isinstance(actual_fast, bool):
  2779. state.actual_fast_mode = actual_fast
  2780. state.terminal_info_received.set()
  2781. await self._finalize_state_locked(
  2782. state,
  2783. outcome=state.terminal_status or "failed",
  2784. error=state.terminal_error,
  2785. stored_session_id=rotated,
  2786. interrupt=False,
  2787. )
  2788. return
  2789. if event_type == "error":
  2790. await self._flush_streaming(state)
  2791. await self._finalize_state_locked(
  2792. state,
  2793. outcome="failed",
  2794. error="Agent Gateway reported a failure",
  2795. interrupt=True,
  2796. )
  2797. @staticmethod
  2798. def _require_safe_control_payload(
  2799. event_type: str, payload: Mapping[str, object]
  2800. ) -> None:
  2801. truncated = payload.get("truncatedFields")
  2802. invalid = payload.get("invalidFields")
  2803. truncated_fields = (
  2804. {item for item in truncated if isinstance(item, str)}
  2805. if isinstance(truncated, list)
  2806. else set()
  2807. )
  2808. invalid_fields = (
  2809. {item for item in invalid if isinstance(item, str)}
  2810. if isinstance(invalid, list)
  2811. else set()
  2812. )
  2813. if payload.get("transportInvalidPayload") is True and not invalid_fields:
  2814. raise GroupOrchestratorError("Gateway control payload is invalid")
  2815. critical: set[str]
  2816. if event_type == "message.complete":
  2817. critical = {"status", "text", "reasoning"}
  2818. elif event_type == "session.info":
  2819. critical = {"running", "stored_session_id", "profile_name"}
  2820. elif event_type in {"approval.request", "clarify.request"}:
  2821. if payload.get("transportTruncated") is True:
  2822. raise GroupOrchestratorError(
  2823. "Gateway interaction request was truncated"
  2824. )
  2825. critical = {
  2826. "request_id",
  2827. "question",
  2828. "command",
  2829. "choices",
  2830. "tool",
  2831. "name",
  2832. }
  2833. elif event_type == "clarify.expire":
  2834. critical = {"request_id"}
  2835. elif event_type.startswith("tool."):
  2836. critical = {"tool_id", "id"}
  2837. if event_type == "tool.output_risk":
  2838. critical |= {"risk", "redacted"}
  2839. elif event_type == "error":
  2840. critical = {"message", "error", "reason"}
  2841. else:
  2842. critical = set()
  2843. if critical & (truncated_fields | invalid_fields):
  2844. raise GroupOrchestratorError(
  2845. "Gateway control payload lost a critical field"
  2846. )
  2847. if payload.get("transportInvalidPayload") is True:
  2848. # Known-invalid non-critical diagnostics never justify trusting an
  2849. # approval/tool/terminal control frame as authoritative.
  2850. if event_type != "session.info":
  2851. raise GroupOrchestratorError("Gateway control payload is invalid")
  2852. if (
  2853. payload.get("transportTruncated") is True
  2854. and not truncated_fields
  2855. and event_type
  2856. in {
  2857. "message.complete",
  2858. "session.info",
  2859. "approval.request",
  2860. "clarify.request",
  2861. "clarify.expire",
  2862. }
  2863. ):
  2864. raise GroupOrchestratorError("Gateway control payload was replaced")
  2865. async def _flush_streaming(self, state: _RuntimeState) -> None:
  2866. if not state.stream_dirty:
  2867. return
  2868. if state.reply_mode == "automatic" and not state.automatic_published:
  2869. return
  2870. await self._persist_message_snapshot(state, status="streaming")
  2871. state.stream_dirty = False
  2872. state.last_stream_flush = asyncio.get_running_loop().time()
  2873. async def _persist_message_snapshot(
  2874. self,
  2875. state: _RuntimeState,
  2876. *,
  2877. status: str,
  2878. error: str = "",
  2879. publish: bool | None = None,
  2880. ) -> None:
  2881. should_publish = (
  2882. state.reply_mode == "mentioned" or state.automatic_published
  2883. if publish is None
  2884. else publish
  2885. )
  2886. content = (
  2887. _sanitize_no_reply_text(state.content)
  2888. if state.reply_mode == "automatic"
  2889. else state.content
  2890. )
  2891. reasoning = (
  2892. _sanitize_no_reply_text(state.reasoning)
  2893. if state.reply_mode == "automatic"
  2894. else state.reasoning
  2895. )
  2896. persisted = False
  2897. for delay in (*_STORE_RETRY_DELAYS, None):
  2898. try:
  2899. await self._run_state_blocking(
  2900. state,
  2901. self.store.upsert_agent_message,
  2902. state.run_id,
  2903. content=content,
  2904. reasoning=reasoning,
  2905. tool_state=state.tool_state,
  2906. status=status,
  2907. error=error,
  2908. publish=should_publish,
  2909. )
  2910. persisted = True
  2911. break
  2912. except Exception: # noqa: BLE001 - reconcile a lost Store reply
  2913. try:
  2914. persisted = bool(
  2915. await self._run_state_blocking(
  2916. state,
  2917. self._terminal_message_is_durable,
  2918. state,
  2919. content=content,
  2920. reasoning=reasoning,
  2921. tool_state=state.tool_state,
  2922. status=status,
  2923. error=error,
  2924. )
  2925. )
  2926. except Exception: # noqa: BLE001 - retry the exact snapshot
  2927. persisted = False
  2928. if persisted:
  2929. break
  2930. if delay is None:
  2931. break
  2932. await asyncio.sleep(delay)
  2933. if not persisted:
  2934. raise GroupOrchestratorError("Agent message snapshot is not durable")
  2935. async def _publish_automatic_state(self, state: _RuntimeState) -> None:
  2936. if state.reply_mode != "automatic" or state.automatic_published:
  2937. return
  2938. state.automatic_published = True
  2939. await self._persist_message_snapshot(state, status="streaming", publish=True)
  2940. state.stream_dirty = False
  2941. state.last_stream_flush = asyncio.get_running_loop().time()
  2942. @staticmethod
  2943. def _bounded_text(value: str, field_name: str) -> str:
  2944. try:
  2945. size = len(value.encode("utf-8"))
  2946. except UnicodeEncodeError as error:
  2947. raise GroupOrchestratorError(
  2948. f"Gateway {field_name} is not valid UTF-8"
  2949. ) from error
  2950. if size > MAX_MESSAGE_BYTES:
  2951. raise GroupOrchestratorError(
  2952. f"Gateway {field_name} exceeds the group message limit"
  2953. )
  2954. return value
  2955. @classmethod
  2956. def _append_bounded_text(cls, existing: str, delta: str, field_name: str) -> str:
  2957. return cls._bounded_text(existing + delta, field_name)
  2958. def _merge_tool_event(
  2959. self,
  2960. state: _RuntimeState,
  2961. event_type: str,
  2962. payload: Mapping[str, object],
  2963. ) -> None:
  2964. if payload.get("transportInvalidPayload") is True:
  2965. raise GroupOrchestratorError("Gateway tool payload is invalid")
  2966. tool_id = payload.get("tool_id", payload.get("id"))
  2967. tool_id = _required_string(tool_id, "tool.tool_id")
  2968. if tool_id == _TOOL_TRUNCATION_ID:
  2969. raise GroupOrchestratorError("Gateway tool id is reserved")
  2970. if len(tool_id.encode("utf-8")) > _TOOL_TEXT_LIMIT:
  2971. raise GroupOrchestratorError("Gateway tool id exceeds the limit")
  2972. name_value = payload.get("name")
  2973. name = (
  2974. self._bounded_tool_text(name_value)
  2975. if isinstance(name_value, str) and name_value
  2976. else None
  2977. )
  2978. existing = self._tool_state_for_id(state, tool_id)
  2979. tool: dict[str, object] = (
  2980. dict(existing)
  2981. if existing is not None
  2982. else {"id": tool_id, "name": name or "unknown", "status": "running"}
  2983. )
  2984. if name is not None:
  2985. tool["name"] = name
  2986. if "args" in payload:
  2987. tool["arguments"] = self._bounded_tool_value(payload["args"], "tool.args")
  2988. elif "args_text" in payload:
  2989. args_text = payload["args_text"]
  2990. if not isinstance(args_text, str):
  2991. raise GroupOrchestratorError("Gateway tool args_text is invalid")
  2992. tool["arguments"] = self._bounded_tool_text(args_text)
  2993. if event_type == "tool.output_risk":
  2994. output_risk, risk_preview = self._project_output_risk(payload)
  2995. tool["outputRisk"] = output_risk
  2996. tool["preview"] = risk_preview
  2997. preview = next(
  2998. (
  2999. value
  3000. for key in ("summary", "context", "result_text", "args_text")
  3001. if isinstance((value := payload.get(key)), str) and value
  3002. ),
  3003. None,
  3004. )
  3005. if preview is not None and event_type != "tool.output_risk":
  3006. tool["preview"] = self._bounded_tool_text(preview)
  3007. if "result" in payload:
  3008. tool["result"] = self._bounded_tool_value(payload["result"], "tool.result")
  3009. error = payload.get("error")
  3010. if isinstance(error, str) and error:
  3011. tool["error"] = self._bounded_tool_text(error)
  3012. duration = payload.get("duration_s")
  3013. if (
  3014. isinstance(duration, (int, float))
  3015. and not isinstance(duration, bool)
  3016. and math.isfinite(duration)
  3017. and duration >= 0
  3018. ):
  3019. tool["durationSeconds"] = float(duration)
  3020. if event_type == "tool.complete":
  3021. raw_status = payload.get("status")
  3022. tool["status"] = (
  3023. "failed"
  3024. if tool.get("error")
  3025. or raw_status in {"error", "failed", "cancelled", "canceled"}
  3026. else "completed"
  3027. )
  3028. elif existing is None:
  3029. tool["status"] = "running"
  3030. self._upsert_tool_state(state, tool)
  3031. @staticmethod
  3032. def _bounded_tool_text(value: str, limit: int = _TOOL_TEXT_LIMIT) -> str:
  3033. try:
  3034. encoded = value.encode("utf-8")
  3035. except UnicodeEncodeError as error:
  3036. raise GroupOrchestratorError(
  3037. "Gateway tool text is not valid UTF-8"
  3038. ) from error
  3039. if len(encoded) <= limit:
  3040. return value
  3041. suffix = "..."
  3042. prefix = encoded[: limit - len(suffix)]
  3043. while prefix:
  3044. try:
  3045. return prefix.decode("utf-8") + suffix
  3046. except UnicodeDecodeError:
  3047. prefix = prefix[:-1]
  3048. return suffix
  3049. @classmethod
  3050. def _bounded_tool_value(cls, value: object, field_name: str) -> object:
  3051. copied = _strict_json_copy(value, field_name)
  3052. encoded = json.dumps(
  3053. copied,
  3054. ensure_ascii=False,
  3055. sort_keys=True,
  3056. separators=(",", ":"),
  3057. allow_nan=False,
  3058. ).encode("utf-8")
  3059. if len(encoded) <= _TOOL_VALUE_LIMIT:
  3060. return copied
  3061. return {"originalBytes": len(encoded), "truncated": True}
  3062. @classmethod
  3063. def _project_output_risk(
  3064. cls, payload: Mapping[str, object]
  3065. ) -> tuple[dict[str, object], str]:
  3066. risk_value = payload.get("risk")
  3067. findings_value = payload.get("findings")
  3068. redacted = payload.get("redacted")
  3069. if not isinstance(risk_value, str) or not risk_value:
  3070. raise GroupOrchestratorError("Gateway tool output risk is invalid")
  3071. if not isinstance(findings_value, list) or not all(
  3072. isinstance(item, str) for item in findings_value
  3073. ):
  3074. raise GroupOrchestratorError("Gateway tool output findings are invalid")
  3075. if not isinstance(redacted, bool):
  3076. raise GroupOrchestratorError("Gateway tool output redaction is invalid")
  3077. risk = cls._bounded_tool_text(risk_value, 256)
  3078. findings = [
  3079. cls._bounded_tool_text(item, 512)
  3080. for item in findings_value[:_TOOL_FINDING_LIMIT]
  3081. ]
  3082. truncated = (
  3083. len(findings_value) > len(findings)
  3084. or risk != risk_value
  3085. or any(
  3086. projected != original
  3087. for projected, original in zip(findings, findings_value)
  3088. )
  3089. )
  3090. transport_truncated = payload.get("truncatedFields")
  3091. if isinstance(transport_truncated, list) and "findings" in transport_truncated:
  3092. truncated = True
  3093. output_risk: dict[str, object] = {
  3094. "risk": risk,
  3095. "findings": findings,
  3096. "redacted": redacted,
  3097. }
  3098. if truncated:
  3099. output_risk["truncated"] = True
  3100. preview = f"Output risk: {risk}"
  3101. if findings:
  3102. preview += "; findings: " + ", ".join(findings)
  3103. preview += f"; redacted: {'true' if redacted else 'false'}"
  3104. return output_risk, cls._bounded_tool_text(preview)
  3105. @staticmethod
  3106. def _tool_state_for_id(
  3107. state: _RuntimeState, tool_id: str
  3108. ) -> dict[str, object] | None:
  3109. index = state.tool_indexes.get(tool_id)
  3110. return None if index is None else state.tool_state[index]
  3111. @classmethod
  3112. def _upsert_tool_state(cls, state: _RuntimeState, tool: dict[str, object]) -> None:
  3113. tool_id = str(tool["id"])
  3114. index = state.tool_indexes.get(tool_id)
  3115. candidate = [dict(item) for item in state.tool_state]
  3116. if index is None:
  3117. candidate.append(dict(tool))
  3118. else:
  3119. candidate[index] = dict(tool)
  3120. candidate = cls._fit_tool_state(candidate, newest_tool_id=tool_id)
  3121. state.tool_state = candidate
  3122. state.tool_indexes = {
  3123. str(item["id"]): offset for offset, item in enumerate(candidate)
  3124. }
  3125. @classmethod
  3126. def _fit_tool_state(
  3127. cls,
  3128. candidate: list[dict[str, object]],
  3129. *,
  3130. newest_tool_id: str,
  3131. ) -> list[dict[str, object]]:
  3132. def encoded_size(items: list[dict[str, object]]) -> int:
  3133. try:
  3134. return len(
  3135. json.dumps(
  3136. items,
  3137. ensure_ascii=False,
  3138. sort_keys=True,
  3139. separators=(",", ":"),
  3140. allow_nan=False,
  3141. ).encode("utf-8")
  3142. )
  3143. except (TypeError, ValueError, UnicodeEncodeError) as error:
  3144. raise GroupOrchestratorError("Gateway tool state is invalid") from error
  3145. if (
  3146. len(candidate) <= _TOOL_COUNT_LIMIT
  3147. and encoded_size(candidate) <= _TOOL_STATE_INTERNAL_LIMIT
  3148. ):
  3149. return candidate
  3150. newest = next(
  3151. (item for item in candidate if item.get("id") == newest_tool_id), None
  3152. )
  3153. if newest is None:
  3154. raise GroupOrchestratorError("Gateway tool state merge lost its tool")
  3155. retained = [
  3156. item
  3157. for item in candidate
  3158. if item.get("id") not in {newest_tool_id, _TOOL_TRUNCATION_ID}
  3159. ]
  3160. marker = {
  3161. "id": _TOOL_TRUNCATION_ID,
  3162. "name": "hermes",
  3163. "status": "completed",
  3164. "preview": "Earlier tool state omitted by the group size limit",
  3165. }
  3166. fitted = [*retained, marker, newest]
  3167. while (
  3168. len(fitted) > _TOOL_COUNT_LIMIT
  3169. or encoded_size(fitted) > _TOOL_STATE_INTERNAL_LIMIT
  3170. ):
  3171. if not retained:
  3172. break
  3173. retained.pop(0)
  3174. fitted = [*retained, marker, newest]
  3175. if (
  3176. len(fitted) > _TOOL_COUNT_LIMIT
  3177. or encoded_size(fitted) > _TOOL_STATE_INTERNAL_LIMIT
  3178. ):
  3179. compact_newest: dict[str, object] = {
  3180. "id": newest_tool_id,
  3181. "name": cls._bounded_tool_text(
  3182. str(newest.get("name") or "unknown"), 256
  3183. ),
  3184. "status": str(newest.get("status") or "running"),
  3185. "preview": cls._bounded_tool_text(
  3186. str(newest.get("preview") or "Tool state truncated"), 4096
  3187. ),
  3188. }
  3189. output_risk = newest.get("outputRisk")
  3190. if isinstance(output_risk, Mapping):
  3191. compact_newest["outputRisk"] = {
  3192. "risk": cls._bounded_tool_text(
  3193. str(output_risk.get("risk") or "unknown"), 256
  3194. ),
  3195. "findings": [
  3196. cls._bounded_tool_text(item, 512)
  3197. for item in output_risk.get("findings", [])[
  3198. :_TOOL_FINDING_LIMIT
  3199. ]
  3200. if isinstance(item, str)
  3201. ],
  3202. "redacted": output_risk.get("redacted") is True,
  3203. "truncated": True,
  3204. }
  3205. fitted = [marker, compact_newest]
  3206. if encoded_size(fitted) > MAX_TOOL_STATE_BYTES:
  3207. raise GroupOrchestratorError("Gateway tool state exceeds the limit")
  3208. return fitted
  3209. async def _store_retry(
  3210. self,
  3211. state: _RuntimeState,
  3212. function: Callable[..., object],
  3213. *args: object,
  3214. **kwargs: object,
  3215. ) -> object:
  3216. last_error: Exception | None = None
  3217. for delay in (*_STORE_RETRY_DELAYS, None):
  3218. try:
  3219. return await self._run_state_blocking(state, function, *args, **kwargs)
  3220. except Exception as error: # noqa: BLE001 - exact Store APIs replay
  3221. last_error = error
  3222. if delay is None:
  3223. break
  3224. await asyncio.sleep(delay)
  3225. if last_error is None:
  3226. raise GroupOrchestratorError("Store operation failed")
  3227. raise last_error
  3228. async def _persist_approval(
  3229. self, state: _RuntimeState, payload: Mapping[str, object]
  3230. ) -> None:
  3231. if payload.get("transportInvalidPayload") is True:
  3232. raise GroupOrchestratorError("Gateway approval payload is invalid")
  3233. raw_choices = payload.get("choices")
  3234. if raw_choices is None:
  3235. choices = ["deny"]
  3236. elif (
  3237. not isinstance(raw_choices, list)
  3238. or not raw_choices
  3239. or not all(
  3240. isinstance(choice, str) and choice in _APPROVAL_CHOICES
  3241. for choice in raw_choices
  3242. )
  3243. ):
  3244. raise GroupOrchestratorError("Gateway approval choices are invalid")
  3245. else:
  3246. choices = list(dict.fromkeys(raw_choices))
  3247. safe_payload = dict(payload)
  3248. safe_payload["choices"] = choices
  3249. state.approval_ordinal += 1
  3250. interaction_id = "approval-" + str(
  3251. uuid.uuid5(
  3252. uuid.NAMESPACE_URL,
  3253. f"{state.run_id}:{state.generation}:approval:{state.approval_ordinal}",
  3254. )
  3255. )
  3256. interaction = await self._store_retry(
  3257. state,
  3258. self.store.create_gateway_interaction,
  3259. state.run_id,
  3260. kind="approval",
  3261. gateway_interaction_id=interaction_id,
  3262. payload=safe_payload,
  3263. )
  3264. if not isinstance(interaction, Mapping):
  3265. raise GroupOrchestratorError("Stored approval is invalid")
  3266. local_id = _required_string(interaction.get("id"), "interaction.id")
  3267. state.had_visible_interaction = True
  3268. state.pending_interaction_ids.add(local_id)
  3269. async def _persist_clarification(
  3270. self, state: _RuntimeState, payload: Mapping[str, object]
  3271. ) -> None:
  3272. if payload.get("transportInvalidPayload") is True:
  3273. raise GroupOrchestratorError("Gateway clarification payload is invalid")
  3274. request_id = _required_string(
  3275. payload.get("request_id"), "clarification.request_id"
  3276. )
  3277. interaction = await self._store_retry(
  3278. state,
  3279. self.store.create_gateway_interaction,
  3280. state.run_id,
  3281. kind="clarification",
  3282. gateway_interaction_id=request_id,
  3283. payload=dict(payload),
  3284. )
  3285. if not isinstance(interaction, Mapping):
  3286. raise GroupOrchestratorError("Stored clarification is invalid")
  3287. local_id = _required_string(interaction.get("id"), "interaction.id")
  3288. state.had_visible_interaction = True
  3289. state.clarification_ids[request_id] = local_id
  3290. state.pending_interaction_ids.add(local_id)
  3291. async def _expire_clarification(
  3292. self, state: _RuntimeState, payload: Mapping[str, object]
  3293. ) -> None:
  3294. request_id = _required_string(
  3295. payload.get("request_id"), "clarification.request_id"
  3296. )
  3297. local_id = state.clarification_ids.get(request_id)
  3298. if local_id is None:
  3299. return
  3300. await self._store_retry(state, self.store.expire_interaction, local_id)
  3301. state.pending_interaction_ids.discard(local_id)
  3302. async def _expire_pending_interactions(self, state: _RuntimeState) -> None:
  3303. for interaction_id in tuple(sorted(state.pending_interaction_ids)):
  3304. await self._store_retry(
  3305. state, self.store.expire_interaction, interaction_id
  3306. )
  3307. state.pending_interaction_ids.discard(interaction_id)
  3308. def _terminal_message_is_durable(
  3309. self,
  3310. state: _RuntimeState,
  3311. *,
  3312. content: str,
  3313. reasoning: str,
  3314. tool_state: list[dict[str, object]],
  3315. status: str,
  3316. error: str,
  3317. ) -> bool:
  3318. """Reconcile a lost Store reply without accepting another run's write."""
  3319. run = self.store.get_run(state.run_id)
  3320. if not isinstance(run, Mapping):
  3321. return False
  3322. response_message_id = run.get("responseMessageId")
  3323. if not isinstance(response_message_id, str) or not response_message_id:
  3324. return False
  3325. if (
  3326. run.get("id") != state.run_id
  3327. or run.get("roomId") != state.room_id
  3328. or run.get("agentId") != state.agent_id
  3329. or run.get("runtimeSessionId") != state.runtime_id
  3330. or run.get("status") not in {"running", "awaiting_input"}
  3331. ):
  3332. return False
  3333. message = self.store.get_message(response_message_id)
  3334. if not isinstance(message, Mapping):
  3335. return False
  3336. return (
  3337. message.get("id") == response_message_id
  3338. and message.get("roomId") == state.room_id
  3339. and message.get("senderKind") == "agent"
  3340. and message.get("senderId") == state.agent_id
  3341. and message.get("content") == content
  3342. and message.get("reasoning") == reasoning
  3343. and message.get("toolState") == tool_state
  3344. and message.get("status") == status
  3345. and message.get("error") == error
  3346. )
  3347. async def _run_state_blocking(
  3348. self,
  3349. state: _RuntimeState,
  3350. function: Callable[..., object],
  3351. *args: object,
  3352. **kwargs: object,
  3353. ) -> object:
  3354. """Track a blocking call so shutdown never abandons its worker thread."""
  3355. return await self._run_states_blocking([state], function, *args, **kwargs)
  3356. @staticmethod
  3357. async def _run_states_blocking(
  3358. states: list[_RuntimeState],
  3359. function: Callable[..., object],
  3360. *args: object,
  3361. **kwargs: object,
  3362. ) -> object:
  3363. """Shield one worker call and expose it to every affected runtime."""
  3364. task: asyncio.Task[object] = asyncio.create_task(
  3365. asyncio.to_thread(function, *args, **kwargs)
  3366. )
  3367. unique_states = tuple({id(state): state for state in states}.values())
  3368. for state in unique_states:
  3369. state.inflight_calls.add(task)
  3370. def finished(done: asyncio.Task[object]) -> None:
  3371. for state in unique_states:
  3372. state.inflight_calls.discard(done)
  3373. task.add_done_callback(finished)
  3374. return await asyncio.shield(task)
  3375. async def _await_terminal_info(self, state: _RuntimeState) -> None:
  3376. """Apply the grace timeout only after a terminal message.complete."""
  3377. terminal_wait = asyncio.create_task(state.terminal_info_received.wait())
  3378. finished_wait = asyncio.create_task(state.finished.wait())
  3379. try:
  3380. done, pending = await asyncio.wait(
  3381. {terminal_wait, finished_wait},
  3382. timeout=self._completion_timeout,
  3383. return_when=asyncio.FIRST_COMPLETED,
  3384. )
  3385. for waiter in pending:
  3386. waiter.cancel()
  3387. if terminal_wait in done or finished_wait in done:
  3388. return
  3389. await self._finalize_state(
  3390. state,
  3391. outcome=(
  3392. state.terminal_status
  3393. if state.terminal_status in {"failed", "interrupted"}
  3394. else "interrupted"
  3395. ),
  3396. error=state.terminal_error or "Final session state timed out",
  3397. interrupt=True,
  3398. )
  3399. finally:
  3400. for waiter in (terminal_wait, finished_wait):
  3401. if not waiter.done():
  3402. waiter.cancel()
  3403. async def _finalize_state(
  3404. self,
  3405. state: _RuntimeState,
  3406. *,
  3407. outcome: str,
  3408. error: str,
  3409. interrupt: bool,
  3410. stored_session_id: str | None = None,
  3411. ) -> None:
  3412. async with state.mutation_lock:
  3413. await self._finalize_state_locked(
  3414. state,
  3415. outcome=outcome,
  3416. error=error,
  3417. interrupt=interrupt,
  3418. stored_session_id=stored_session_id,
  3419. )
  3420. async def _finalize_state_locked(
  3421. self,
  3422. state: _RuntimeState,
  3423. *,
  3424. outcome: str,
  3425. error: str,
  3426. interrupt: bool,
  3427. stored_session_id: str | None = None,
  3428. ) -> None:
  3429. async with state.finalize_lock:
  3430. if state.finished.is_set():
  3431. return
  3432. state.finalizing = True
  3433. current_task = asyncio.current_task()
  3434. pending_calls = tuple(state.inflight_calls)
  3435. if pending_calls:
  3436. await asyncio.gather(*pending_calls, return_exceptions=True)
  3437. gateway = self._required_gateway()
  3438. if interrupt:
  3439. try:
  3440. await self._run_state_blocking(
  3441. state, gateway.interrupt, state.runtime_id
  3442. )
  3443. except Exception: # noqa: BLE001 - settle remains mandatory
  3444. logger.exception("Failed to interrupt YaoYao group runtime")
  3445. expected_stored = (
  3446. state.session_stored_id
  3447. if state.prompt_committed
  3448. else state.expected_stored_id
  3449. )
  3450. rotated_stored = stored_session_id or state.session_stored_id
  3451. settled = False
  3452. for delay in (*_STORE_RETRY_DELAYS, None):
  3453. try:
  3454. await self._run_state_blocking(
  3455. state,
  3456. self.store.settle_run,
  3457. state.run_id,
  3458. runtime_session_id=state.runtime_id,
  3459. expected_stored_session_id=expected_stored,
  3460. stored_session_id=rotated_stored,
  3461. outcome=outcome,
  3462. actual_model=state.actual_model,
  3463. actual_provider=state.actual_provider,
  3464. actual_reasoning_effort=state.actual_reasoning_effort,
  3465. actual_fast_mode=state.actual_fast_mode,
  3466. error=self._bounded_error(error),
  3467. )
  3468. settled = True
  3469. break
  3470. except Exception: # noqa: BLE001 - reconcile before retrying
  3471. if await self._run_is_durably_terminal(state.run_id):
  3472. settled = True
  3473. break
  3474. if delay is None:
  3475. logger.exception("Failed to settle YaoYao group runtime")
  3476. break
  3477. await asyncio.sleep(delay)
  3478. if not settled:
  3479. state.settle_error = GroupOrchestratorError(
  3480. "Durable runtime settlement failed"
  3481. )
  3482. return
  3483. state.settle_error = None
  3484. self._remove_runtime(state)
  3485. try:
  3486. await self._run_state_blocking(state, gateway.close, state.runtime_id)
  3487. except Exception: # noqa: BLE001 - durable state is already terminal
  3488. logger.exception("Failed to close settled YaoYao group runtime")
  3489. if outcome == "completed":
  3490. try:
  3491. cascade = await self._run_state_blocking(
  3492. state, self.store.complete_cascade, state.run_id
  3493. )
  3494. except Exception: # noqa: BLE001 - source is already durably complete
  3495. logger.error("Pending YaoYao group cascade remains durable")
  3496. self.wake()
  3497. else:
  3498. if (
  3499. isinstance(cascade, Mapping)
  3500. and isinstance(cascade.get("runCount"), int)
  3501. and not isinstance(cascade.get("runCount"), bool)
  3502. and cascade["runCount"] > 0
  3503. ):
  3504. self.wake()
  3505. state.finished.set()
  3506. state.terminal_info_received.set()
  3507. if state.event_task is not None and state.event_task is not current_task:
  3508. if not state.event_task.done():
  3509. state.event_task.cancel()
  3510. await asyncio.gather(state.event_task, return_exceptions=True)
  3511. if state.grace_task is not None and state.grace_task is not current_task:
  3512. if not state.grace_task.done():
  3513. state.grace_task.cancel()
  3514. await asyncio.gather(state.grace_task, return_exceptions=True)
  3515. def _required_gateway(self) -> _Gateway:
  3516. if self._gateway is None:
  3517. raise GroupOrchestratorError("Gateway adapter is not started")
  3518. return self._gateway
  3519. @staticmethod
  3520. def _bounded_error(value: str) -> str:
  3521. encoded = value.encode("utf-8", errors="replace")
  3522. if len(encoded) <= _ERROR_TEXT_LIMIT:
  3523. return value
  3524. shortened = encoded[: _ERROR_TEXT_LIMIT - 3]
  3525. while shortened:
  3526. try:
  3527. return shortened.decode("utf-8") + "..."
  3528. except UnicodeDecodeError:
  3529. shortened = shortened[:-1]
  3530. return "..."
  3531. __all__ = [
  3532. "DEFAULT_COMPLETION_TIMEOUT",
  3533. "DEFAULT_EVENT_QUEUE_SIZE",
  3534. "GroupOrchestrator",
  3535. "GroupOrchestratorError",
  3536. "build_run_prompt",
  3537. ]