group_store.py 203 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934
  1. """Durable SQLite storage primitives for the YaoYao Group Chat plugin."""
  2. from __future__ import annotations
  3. import base64
  4. import binascii
  5. import hashlib
  6. import json
  7. import math
  8. import os
  9. import re
  10. import sqlite3
  11. import time
  12. import unicodedata
  13. import uuid
  14. from contextlib import contextmanager
  15. from dataclasses import dataclass
  16. from pathlib import Path
  17. from typing import Callable, Iterator, Mapping
  18. from .group_protocol import (
  19. ALL_MENTION_ALIASES,
  20. CONTEXT_CHARACTER_BUDGET,
  21. DEFAULT_MAX_REPLY_ROUNDS,
  22. INITIAL_CONTEXT_MESSAGE_LIMIT,
  23. MAX_AGENTS_PER_ROOM,
  24. MAX_EVENT_BATCH_SIZE,
  25. MAX_FINITE_REPLY_ROUNDS,
  26. MAX_INTERACTION_PAYLOAD_BYTES,
  27. MAX_MESSAGE_BYTES,
  28. MAX_MESSAGE_PAGE_SIZE,
  29. MAX_PLUGIN_CONCURRENCY,
  30. MAX_ROOM_CONCURRENCY,
  31. MAX_TOOL_STATE_BYTES,
  32. is_reserved_mention_alias,
  33. normalize_display_name,
  34. normalize_interaction_id,
  35. normalize_max_reply_rounds,
  36. normalize_room_cwd,
  37. normalize_room_name,
  38. )
  39. SCHEMA_VERSION = 3
  40. _WAL_RETRY_DELAYS = (0.01, 0.02, 0.04, 0.08)
  41. EVENT_RETENTION_SECONDS = 30 * 24 * 60 * 60
  42. MIN_RETAINED_EVENTS = 100_000
  43. UNSET = object()
  44. RUN_TRANSITIONS = {
  45. "queued": frozenset({"running", "interrupted", "failed"}),
  46. "running": frozenset({"awaiting_input", "completed", "failed", "interrupted"}),
  47. "awaiting_input": frozenset({"running", "failed", "interrupted"}),
  48. "completed": frozenset(),
  49. "failed": frozenset(),
  50. "interrupted": frozenset(),
  51. }
  52. _MESSAGE_STATUSES = frozenset(
  53. {"queued", "streaming", "completed", "failed", "interrupted"}
  54. )
  55. _AGENT_MESSAGE_STATUSES_BY_RUN = {
  56. "queued": frozenset({"queued"}),
  57. "running": frozenset({"queued", "streaming", "completed"}),
  58. "awaiting_input": frozenset({"queued", "streaming"}),
  59. "completed": frozenset(),
  60. "failed": frozenset(),
  61. "interrupted": frozenset(),
  62. }
  63. _AGENT_MESSAGE_TRANSITIONS = {
  64. "queued": frozenset({"queued", "streaming", "completed"}),
  65. "streaming": frozenset({"streaming", "completed"}),
  66. "completed": frozenset(),
  67. "failed": frozenset(),
  68. "interrupted": frozenset(),
  69. }
  70. _MESSAGE_STATUSES_BY_RUN = {
  71. "queued": frozenset({"queued"}),
  72. "running": frozenset({"queued", "streaming", "completed"}),
  73. "awaiting_input": frozenset({"queued", "streaming"}),
  74. "completed": frozenset({"completed"}),
  75. "failed": frozenset({"failed", "completed"}),
  76. "interrupted": frozenset({"interrupted", "completed"}),
  77. }
  78. _INTERACTION_KINDS = frozenset({"approval", "clarification"})
  79. _INTERACTION_TERMINAL_STATUSES = frozenset({"resolved", "cancelled"})
  80. _CASCADE_PENDING_OPERATION = "internal.cascade.pending"
  81. _CASCADE_COMPLETED_OPERATION = "internal.cascade.completed"
  82. _CASCADE_DISCARDED_OPERATION = "internal.cascade.discarded"
  83. _CASCADE_OPERATIONS = frozenset(
  84. {
  85. _CASCADE_PENDING_OPERATION,
  86. _CASCADE_COMPLETED_OPERATION,
  87. _CASCADE_DISCARDED_OPERATION,
  88. }
  89. )
  90. _CASCADE_PARSE_VERSION = 2
  91. _MAX_CASCADE_PAGE_SIZE = 32
  92. _MAX_CASCADE_PLAN_BYTES = 16 * 1024
  93. _SCHEMA_STATEMENTS = (
  94. """CREATE TABLE IF NOT EXISTS group_meta (
  95. key TEXT PRIMARY KEY,
  96. value TEXT NOT NULL
  97. )""",
  98. """CREATE TABLE IF NOT EXISTS group_rooms (
  99. id TEXT PRIMARY KEY,
  100. name TEXT NOT NULL,
  101. cwd TEXT NOT NULL DEFAULT '',
  102. max_reply_rounds INTEGER NOT NULL DEFAULT 3,
  103. created_at REAL NOT NULL,
  104. updated_at REAL NOT NULL,
  105. archived INTEGER NOT NULL DEFAULT 0
  106. )""",
  107. """CREATE TABLE IF NOT EXISTS group_agents (
  108. id TEXT PRIMARY KEY,
  109. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  110. profile TEXT NOT NULL,
  111. display_name TEXT NOT NULL,
  112. display_name_key TEXT NOT NULL,
  113. description TEXT NOT NULL DEFAULT '',
  114. stored_session_id TEXT,
  115. last_context_message_seq INTEGER NOT NULL DEFAULT 0,
  116. enabled INTEGER NOT NULL DEFAULT 1,
  117. reply_without_mention INTEGER NOT NULL DEFAULT 0,
  118. model_override TEXT,
  119. provider_override TEXT,
  120. reasoning_effort_override TEXT,
  121. fast_mode_override INTEGER,
  122. session_config_json TEXT,
  123. created_at REAL NOT NULL,
  124. updated_at REAL NOT NULL,
  125. UNIQUE(room_id, profile),
  126. UNIQUE(room_id, display_name_key)
  127. )""",
  128. """CREATE TABLE IF NOT EXISTS group_messages (
  129. seq INTEGER PRIMARY KEY AUTOINCREMENT,
  130. id TEXT NOT NULL UNIQUE,
  131. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  132. sender_kind TEXT NOT NULL,
  133. sender_id TEXT NOT NULL,
  134. sender_name TEXT NOT NULL,
  135. root_message_id TEXT NOT NULL,
  136. reply_to_message_id TEXT,
  137. client_message_id TEXT UNIQUE,
  138. content TEXT NOT NULL DEFAULT '',
  139. reasoning TEXT NOT NULL DEFAULT '',
  140. tool_state_json TEXT NOT NULL DEFAULT '[]',
  141. status TEXT NOT NULL,
  142. error TEXT NOT NULL DEFAULT '',
  143. visible INTEGER NOT NULL DEFAULT 1,
  144. created_at REAL NOT NULL,
  145. updated_at REAL NOT NULL
  146. )""",
  147. """CREATE TABLE IF NOT EXISTS group_agent_runs (
  148. id TEXT PRIMARY KEY,
  149. room_id TEXT NOT NULL,
  150. agent_id TEXT NOT NULL,
  151. trigger_message_id TEXT NOT NULL,
  152. response_message_id TEXT NOT NULL,
  153. root_message_id TEXT NOT NULL,
  154. depth INTEGER NOT NULL,
  155. reply_mode TEXT NOT NULL DEFAULT 'mentioned',
  156. status TEXT NOT NULL,
  157. runtime_session_id TEXT,
  158. error TEXT NOT NULL DEFAULT '',
  159. created_at REAL NOT NULL,
  160. updated_at REAL NOT NULL
  161. )""",
  162. """CREATE TABLE IF NOT EXISTS group_interactions (
  163. id TEXT PRIMARY KEY,
  164. room_id TEXT NOT NULL,
  165. agent_id TEXT NOT NULL,
  166. run_id TEXT NOT NULL,
  167. kind TEXT NOT NULL,
  168. payload_json TEXT NOT NULL,
  169. status TEXT NOT NULL,
  170. created_at REAL NOT NULL,
  171. resolved_at REAL
  172. )""",
  173. """CREATE TABLE IF NOT EXISTS group_events (
  174. cursor INTEGER PRIMARY KEY AUTOINCREMENT,
  175. epoch TEXT NOT NULL,
  176. room_id TEXT,
  177. event_type TEXT NOT NULL,
  178. payload_json TEXT NOT NULL,
  179. created_at REAL NOT NULL
  180. )""",
  181. """CREATE TABLE IF NOT EXISTS group_idempotency (
  182. request_id TEXT PRIMARY KEY,
  183. operation TEXT NOT NULL,
  184. request_hash TEXT NOT NULL,
  185. response_json TEXT NOT NULL,
  186. created_at REAL NOT NULL
  187. )""",
  188. "CREATE INDEX IF NOT EXISTS idx_group_rooms_ordering ON group_rooms(archived, updated_at DESC, id DESC)",
  189. "CREATE INDEX IF NOT EXISTS idx_group_messages_room_seq ON group_messages(room_id, seq)",
  190. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room ON group_agent_runs(room_id)",
  191. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_agent_status ON group_agent_runs(agent_id, status)",
  192. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room_status ON group_agent_runs(room_id, status)",
  193. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_status_order ON group_agent_runs(status, created_at, id)",
  194. """CREATE UNIQUE INDEX IF NOT EXISTS idx_group_agent_runs_active_runtime
  195. ON group_agent_runs(runtime_session_id)
  196. WHERE runtime_session_id IS NOT NULL
  197. AND status IN ('running', 'awaiting_input')""",
  198. "CREATE INDEX IF NOT EXISTS idx_group_interactions_room_agent ON group_interactions(room_id, agent_id)",
  199. "CREATE INDEX IF NOT EXISTS idx_group_interactions_run_status_kind ON group_interactions(run_id, status, kind)",
  200. "CREATE INDEX IF NOT EXISTS idx_group_events_room_created_at ON group_events(room_id, created_at)",
  201. "CREATE INDEX IF NOT EXISTS idx_group_events_created_at ON group_events(created_at)",
  202. "CREATE INDEX IF NOT EXISTS idx_group_idempotency_operation ON group_idempotency(operation)",
  203. )
  204. _EXPECTED_TABLES = frozenset(
  205. {
  206. "group_meta",
  207. "group_rooms",
  208. "group_agents",
  209. "group_messages",
  210. "group_agent_runs",
  211. "group_interactions",
  212. "group_events",
  213. "group_idempotency",
  214. }
  215. )
  216. class GroupStoreError(RuntimeError):
  217. """Raised when the group-chat database is uninitialized or corrupt."""
  218. class GroupNotFoundError(GroupStoreError):
  219. """Raised when a room or agent is absent, or unavailable because it is archived."""
  220. class GroupConflictError(GroupStoreError):
  221. """Raised when a requested room-member invariant would be violated."""
  222. class IdempotencyConflict(GroupStoreError):
  223. """Raised when a request ID is reused for a different operation or payload."""
  224. @dataclass(frozen=True)
  225. class CursorPage:
  226. """A page of room summaries and the opaque cursor for its successor."""
  227. items: list[dict[str, object]]
  228. next_cursor: str | None
  229. class GroupStore:
  230. """The versioned SQLite authority for public group-chat state."""
  231. def __init__(
  232. self,
  233. path: Path,
  234. *,
  235. agent_name_resolver: Callable[[str], str] | None = None,
  236. ):
  237. self.path = Path(path)
  238. self._agent_name_resolver = agent_name_resolver or (lambda _profile: "")
  239. @classmethod
  240. def from_environment(
  241. cls, *, agent_name_resolver: Callable[[str], str] | None = None
  242. ) -> "GroupStore":
  243. hermes_home = Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
  244. return cls(
  245. hermes_home / "plugins" / "yaoyao" / "data" / "group-chat.db",
  246. agent_name_resolver=agent_name_resolver,
  247. )
  248. def connect(self) -> sqlite3.Connection:
  249. self.path.parent.mkdir(parents=True, exist_ok=True)
  250. connection = sqlite3.connect(self.path, timeout=5, isolation_level=None)
  251. connection.row_factory = sqlite3.Row
  252. connection.execute("PRAGMA foreign_keys = ON")
  253. connection.execute("PRAGMA busy_timeout = 5000")
  254. return connection
  255. @contextmanager
  256. def connection(self) -> Iterator[sqlite3.Connection]:
  257. """Yield a raw SQLite connection and always close it afterwards."""
  258. connection = self.connect()
  259. try:
  260. yield connection
  261. finally:
  262. connection.close()
  263. def initialize(self) -> None:
  264. """Create or validate the versioned schema without changing its epoch."""
  265. for attempt, delay in enumerate(_WAL_RETRY_DELAYS):
  266. try:
  267. self._initialize_once()
  268. return
  269. except sqlite3.OperationalError as error:
  270. if (
  271. not self._is_busy_or_locked(error)
  272. or attempt == len(_WAL_RETRY_DELAYS) - 1
  273. ):
  274. raise
  275. time.sleep(delay)
  276. def _initialize_once(self) -> None:
  277. with self.connection() as connection:
  278. connection.execute("PRAGMA journal_mode = WAL")
  279. connection.execute("BEGIN IMMEDIATE")
  280. try:
  281. table_names = self._user_table_names(connection)
  282. if not table_names:
  283. self._create_fresh_schema(connection)
  284. else:
  285. self._validate_existing_schema(connection, table_names)
  286. self._ensure_indexes(connection)
  287. self._sync_legacy_fallback_agent_names(connection)
  288. except Exception:
  289. connection.execute("ROLLBACK")
  290. raise
  291. else:
  292. connection.execute("COMMIT")
  293. def _sync_legacy_fallback_agent_names(
  294. self, connection: sqlite3.Connection
  295. ) -> None:
  296. """Adopt configured names for active legacy members without overriding edits."""
  297. rows = connection.execute(
  298. """SELECT group_agents.* FROM group_agents
  299. JOIN group_rooms ON group_rooms.id = group_agents.room_id
  300. WHERE group_agents.display_name = group_agents.profile
  301. AND group_rooms.archived = 0
  302. ORDER BY group_rooms.created_at ASC, group_rooms.id ASC,
  303. group_agents.created_at ASC, group_agents.id ASC"""
  304. ).fetchall()
  305. for row in rows:
  306. configured = self._resolved_agent_name(row["profile"])
  307. if not configured:
  308. continue
  309. try:
  310. display_name, display_name_key = normalize_display_name(configured)
  311. except ValueError:
  312. continue
  313. if (
  314. display_name == row["display_name"]
  315. and display_name_key == row["display_name_key"]
  316. ):
  317. continue
  318. conflict = connection.execute(
  319. """SELECT 1 FROM group_agents
  320. WHERE room_id = ? AND display_name_key = ? AND id != ?
  321. LIMIT 1""",
  322. (row["room_id"], display_name_key, row["id"]),
  323. ).fetchone()
  324. if conflict is not None:
  325. continue
  326. now = self._now()
  327. connection.execute(
  328. """UPDATE group_agents
  329. SET display_name = ?, display_name_key = ?, updated_at = ?
  330. WHERE id = ? AND room_id = ?""",
  331. (display_name, display_name_key, now, row["id"], row["room_id"]),
  332. )
  333. connection.execute(
  334. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  335. (now, row["room_id"]),
  336. )
  337. agent = self._agent_detail(connection, row["room_id"], row["id"])
  338. self._append_event(
  339. connection,
  340. row["room_id"],
  341. "agent.updated",
  342. agent,
  343. created_at=now,
  344. )
  345. self._append_room_updated_summary(
  346. connection, row["room_id"], created_at=now
  347. )
  348. def schema_version(self) -> int:
  349. value = self._metadata_value("schema_version")
  350. return self._validated_schema_version(value)
  351. def journal_epoch(self) -> str:
  352. value = self._metadata_value("journal_epoch")
  353. try:
  354. canonical = str(uuid.UUID(value))
  355. except (ValueError, AttributeError) as error:
  356. raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
  357. if value != canonical:
  358. raise GroupStoreError("GroupStore journal_epoch is corrupt")
  359. return canonical
  360. def _create_fresh_schema(self, connection: sqlite3.Connection) -> None:
  361. for statement in _SCHEMA_STATEMENTS:
  362. connection.execute(statement)
  363. connection.execute(
  364. "INSERT INTO group_meta(key, value) VALUES ('schema_version', ?)",
  365. (str(SCHEMA_VERSION),),
  366. )
  367. connection.execute(
  368. "INSERT INTO group_meta(key, value) VALUES ('journal_epoch', ?)",
  369. (str(uuid.uuid4()),),
  370. )
  371. def _validate_existing_schema(
  372. self, connection: sqlite3.Connection, table_names: set[str]
  373. ) -> None:
  374. if table_names != _EXPECTED_TABLES:
  375. raise GroupStoreError("GroupStore schema is partial or corrupt")
  376. raw_version = self._metadata_value_from_connection(connection, "schema_version")
  377. if raw_version == "1":
  378. self._migrate_v1_to_v2(connection)
  379. raw_version = "2"
  380. if raw_version == "2":
  381. self._migrate_v2_to_v3(connection)
  382. self._validated_schema_version(
  383. self._metadata_value_from_connection(connection, "schema_version")
  384. )
  385. self._validated_epoch(
  386. self._metadata_value_from_connection(connection, "journal_epoch")
  387. )
  388. self._validate_v3_columns(connection)
  389. self._validate_v3_values(connection)
  390. @staticmethod
  391. def _migrate_v1_to_v2(connection: sqlite3.Connection) -> None:
  392. connection.execute(
  393. "ALTER TABLE group_rooms ADD COLUMN max_reply_rounds INTEGER NOT NULL DEFAULT 3"
  394. )
  395. connection.execute(
  396. "ALTER TABLE group_agents ADD COLUMN reply_without_mention INTEGER NOT NULL DEFAULT 0"
  397. )
  398. connection.execute(
  399. "ALTER TABLE group_messages ADD COLUMN visible INTEGER NOT NULL DEFAULT 1"
  400. )
  401. connection.execute(
  402. "ALTER TABLE group_agent_runs ADD COLUMN reply_mode TEXT NOT NULL DEFAULT 'mentioned'"
  403. )
  404. connection.execute(
  405. "UPDATE group_meta SET value = '2' WHERE key = 'schema_version'"
  406. )
  407. @staticmethod
  408. def _migrate_v2_to_v3(connection: sqlite3.Connection) -> None:
  409. connection.execute("ALTER TABLE group_agents ADD COLUMN model_override TEXT")
  410. connection.execute("ALTER TABLE group_agents ADD COLUMN provider_override TEXT")
  411. connection.execute(
  412. "ALTER TABLE group_agents ADD COLUMN reasoning_effort_override TEXT"
  413. )
  414. connection.execute(
  415. "ALTER TABLE group_agents ADD COLUMN fast_mode_override INTEGER"
  416. )
  417. connection.execute(
  418. "ALTER TABLE group_agents ADD COLUMN session_config_json TEXT"
  419. )
  420. connection.execute(
  421. "UPDATE group_meta SET value = '3' WHERE key = 'schema_version'"
  422. )
  423. @staticmethod
  424. def _validate_v3_columns(connection: sqlite3.Connection) -> None:
  425. expected_columns = {
  426. "group_meta": {"key", "value"},
  427. "group_rooms": {"id", "name", "cwd", "max_reply_rounds", "created_at", "updated_at", "archived"},
  428. "group_agents": {"id", "room_id", "profile", "display_name", "display_name_key", "description", "stored_session_id", "last_context_message_seq", "enabled", "reply_without_mention", "model_override", "provider_override", "reasoning_effort_override", "fast_mode_override", "session_config_json", "created_at", "updated_at"},
  429. "group_messages": {"seq", "id", "room_id", "sender_kind", "sender_id", "sender_name", "root_message_id", "reply_to_message_id", "client_message_id", "content", "reasoning", "tool_state_json", "status", "error", "visible", "created_at", "updated_at"},
  430. "group_agent_runs": {"id", "room_id", "agent_id", "trigger_message_id", "response_message_id", "root_message_id", "depth", "reply_mode", "status", "runtime_session_id", "error", "created_at", "updated_at"},
  431. "group_interactions": {"id", "room_id", "agent_id", "run_id", "kind", "payload_json", "status", "created_at", "resolved_at"},
  432. "group_events": {"cursor", "epoch", "room_id", "event_type", "payload_json", "created_at"},
  433. "group_idempotency": {"request_id", "operation", "request_hash", "response_json", "created_at"},
  434. }
  435. exact_specs = {
  436. ("group_rooms", "max_reply_rounds"): ("INTEGER", 1, "3"),
  437. ("group_agents", "reply_without_mention"): ("INTEGER", 1, "0"),
  438. ("group_messages", "visible"): ("INTEGER", 1, "1"),
  439. ("group_agent_runs", "reply_mode"): ("TEXT", 1, "'mentioned'"),
  440. }
  441. for table, required in expected_columns.items():
  442. rows = list(connection.execute(f"PRAGMA table_info({table})"))
  443. columns = {row["name"]: row for row in rows}
  444. if set(columns) != required:
  445. raise GroupStoreError("GroupStore schema is partial or corrupt")
  446. for (target_table, name), spec in exact_specs.items():
  447. if target_table != table:
  448. continue
  449. row = columns[name]
  450. actual = (str(row["type"]).upper(), int(row["notnull"]), row["dflt_value"])
  451. if actual != spec:
  452. raise GroupStoreError("GroupStore schema is partial or corrupt")
  453. @staticmethod
  454. def _validate_v3_values(connection: sqlite3.Connection) -> None:
  455. invalid_value_queries = (
  456. f"""SELECT 1 FROM group_rooms
  457. WHERE typeof(max_reply_rounds) != 'integer'
  458. OR (max_reply_rounds != -1 AND
  459. (max_reply_rounds < 1 OR
  460. max_reply_rounds > {MAX_FINITE_REPLY_ROUNDS}))
  461. LIMIT 1""",
  462. """SELECT 1 FROM group_agents
  463. WHERE typeof(reply_without_mention) != 'integer'
  464. OR reply_without_mention NOT IN (0, 1)
  465. LIMIT 1""",
  466. """SELECT 1 FROM group_agents
  467. WHERE fast_mode_override IS NOT NULL
  468. AND (typeof(fast_mode_override) != 'integer'
  469. OR fast_mode_override NOT IN (0, 1))
  470. LIMIT 1""",
  471. """SELECT 1 FROM group_agents
  472. WHERE reasoning_effort_override IS NOT NULL
  473. AND reasoning_effort_override NOT IN
  474. ('none','minimal','low','medium','high','xhigh','max','ultra')
  475. LIMIT 1""",
  476. """SELECT 1 FROM group_messages
  477. WHERE typeof(visible) != 'integer'
  478. OR visible NOT IN (0, 1)
  479. LIMIT 1""",
  480. """SELECT 1 FROM group_agent_runs
  481. WHERE typeof(reply_mode) != 'text'
  482. OR reply_mode NOT IN ('mentioned', 'automatic')
  483. LIMIT 1""",
  484. )
  485. for query in invalid_value_queries:
  486. if connection.execute(query).fetchone() is not None:
  487. raise GroupStoreError("GroupStore stored values are corrupt")
  488. @staticmethod
  489. def _ensure_indexes(connection: sqlite3.Connection) -> None:
  490. """Repair v1 operational indexes without a schema-version migration."""
  491. def canonical_index_sql(value: str) -> str:
  492. without_guard = re.sub(
  493. r"\bIF\s+NOT\s+EXISTS\b", "", value, flags=re.IGNORECASE
  494. )
  495. return " ".join(without_guard.split()).casefold()
  496. indexes = {
  497. "idx_group_rooms_ordering": (
  498. [("archived", 0), ("updated_at", 1), ("id", 1)],
  499. "group_rooms(archived, updated_at DESC, id DESC)",
  500. ),
  501. "idx_group_agent_runs_agent_status": (
  502. [("agent_id", 0), ("status", 0)],
  503. "group_agent_runs(agent_id, status)",
  504. ),
  505. "idx_group_agent_runs_room_status": (
  506. [("room_id", 0), ("status", 0)],
  507. "group_agent_runs(room_id, status)",
  508. ),
  509. "idx_group_agent_runs_status_order": (
  510. [("status", 0), ("created_at", 0), ("id", 0)],
  511. "group_agent_runs(status, created_at, id)",
  512. ),
  513. "idx_group_idempotency_operation": (
  514. [("operation", 0)],
  515. "group_idempotency(operation)",
  516. ),
  517. "idx_group_interactions_run_status_kind": (
  518. [("run_id", 0), ("status", 0), ("kind", 0)],
  519. "group_interactions(run_id, status, kind)",
  520. ),
  521. }
  522. for name, (expected, definition) in indexes.items():
  523. columns = [
  524. (row["name"], row["desc"])
  525. for row in connection.execute(f"PRAGMA index_xinfo({name})")
  526. if row["key"]
  527. ]
  528. stored = connection.execute(
  529. """SELECT sql FROM sqlite_master
  530. WHERE type = 'index' AND name = ?""",
  531. (name,),
  532. ).fetchone()
  533. expected_sql = canonical_index_sql(f"CREATE INDEX {name} ON {definition}")
  534. stored_sql = (
  535. None
  536. if stored is None or stored["sql"] is None
  537. else canonical_index_sql(stored["sql"])
  538. )
  539. if columns == expected and stored_sql == expected_sql:
  540. continue
  541. connection.execute(f"DROP INDEX IF EXISTS {name}")
  542. connection.execute(f"CREATE INDEX {name} ON {definition}")
  543. active_runtime_definition = """CREATE UNIQUE INDEX
  544. idx_group_agent_runs_active_runtime
  545. ON group_agent_runs(runtime_session_id)
  546. WHERE runtime_session_id IS NOT NULL
  547. AND status IN ('running', 'awaiting_input')"""
  548. stored = connection.execute(
  549. """SELECT sql FROM sqlite_master
  550. WHERE type = 'index' AND name = ?""",
  551. ("idx_group_agent_runs_active_runtime",),
  552. ).fetchone()
  553. expected_sql = canonical_index_sql(active_runtime_definition)
  554. stored_sql = (
  555. None
  556. if stored is None or stored["sql"] is None
  557. else canonical_index_sql(stored["sql"])
  558. )
  559. if stored_sql == expected_sql:
  560. return
  561. connection.execute("DROP INDEX IF EXISTS idx_group_agent_runs_active_runtime")
  562. try:
  563. connection.execute(active_runtime_definition)
  564. except sqlite3.IntegrityError as error:
  565. raise GroupStoreError("Active runtime sessions are not unique") from error
  566. @staticmethod
  567. def _user_table_names(connection: sqlite3.Connection) -> set[str]:
  568. return {
  569. row["name"]
  570. for row in connection.execute(
  571. """SELECT name FROM sqlite_master
  572. WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
  573. )
  574. }
  575. @staticmethod
  576. def _is_busy_or_locked(error: sqlite3.OperationalError) -> bool:
  577. message = str(error).lower()
  578. return "locked" in message or "busy" in message
  579. @staticmethod
  580. def _validated_schema_version(value: str) -> int:
  581. try:
  582. version = int(value)
  583. except (TypeError, ValueError) as error:
  584. raise GroupStoreError("GroupStore schema_version is corrupt") from error
  585. if value != str(SCHEMA_VERSION) or version != SCHEMA_VERSION:
  586. raise GroupStoreError("Unsupported or corrupt GroupStore schema_version")
  587. return version
  588. def _metadata_value(self, key: str) -> str:
  589. try:
  590. with self.connection() as connection:
  591. return self._metadata_value_from_connection(connection, key)
  592. except sqlite3.OperationalError as error:
  593. raise GroupStoreError("GroupStore is not initialized") from error
  594. @staticmethod
  595. def _metadata_value_from_connection(
  596. connection: sqlite3.Connection, key: str
  597. ) -> str:
  598. row = connection.execute(
  599. "SELECT value FROM group_meta WHERE key = ?", (key,)
  600. ).fetchone()
  601. if row is None:
  602. raise GroupStoreError(f"GroupStore metadata is missing {key}")
  603. return row["value"]
  604. @staticmethod
  605. def _validated_epoch(value: str) -> str:
  606. try:
  607. canonical = str(uuid.UUID(value))
  608. except (ValueError, AttributeError) as error:
  609. raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
  610. if value != canonical:
  611. raise GroupStoreError("GroupStore journal_epoch is corrupt")
  612. return canonical
  613. @contextmanager
  614. def read_transaction(self) -> Iterator[sqlite3.Connection]:
  615. """Yield one consistent read snapshot and always close its connection."""
  616. with self.connection() as connection:
  617. connection.execute("BEGIN")
  618. try:
  619. yield connection
  620. except Exception:
  621. connection.execute("ROLLBACK")
  622. raise
  623. else:
  624. connection.execute("COMMIT")
  625. @contextmanager
  626. def write_transaction(self) -> Iterator[sqlite3.Connection]:
  627. """Yield one immediately-locked write transaction and always close it."""
  628. with self.connection() as connection:
  629. connection.execute("BEGIN IMMEDIATE")
  630. try:
  631. yield connection
  632. except Exception:
  633. connection.execute("ROLLBACK")
  634. raise
  635. else:
  636. connection.execute("COMMIT")
  637. def execute_idempotent(
  638. self,
  639. operation: str,
  640. request_id: str,
  641. payload: Mapping[str, object],
  642. action: Callable[[sqlite3.Connection], dict[str, object]],
  643. ) -> dict[str, object]:
  644. """Execute a mutation exactly once for the canonical request and payload."""
  645. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  646. request_hash = hashlib.sha256(
  647. self._canonical_json(payload).encode()
  648. ).hexdigest()
  649. try:
  650. with self.write_transaction() as connection:
  651. existing = connection.execute(
  652. """SELECT operation, request_hash, response_json FROM group_idempotency
  653. WHERE request_id = ?""",
  654. (canonical_request_id,),
  655. ).fetchone()
  656. if existing is not None:
  657. if (
  658. existing["operation"] != operation
  659. or existing["request_hash"] != request_hash
  660. ):
  661. raise IdempotencyConflict(
  662. "requestId was already used for a different request"
  663. )
  664. stored_response = existing["response_json"]
  665. try:
  666. response = self._load_json(stored_response)
  667. except (ValueError, json.JSONDecodeError, TypeError) as error:
  668. raise GroupStoreError(
  669. "Stored idempotency response is corrupt"
  670. ) from error
  671. if (
  672. not isinstance(response, dict)
  673. or self._canonical_json(response) != stored_response
  674. ):
  675. raise GroupStoreError("Stored idempotency response is corrupt")
  676. return response
  677. response = action(connection)
  678. response_json = self._canonical_json(response)
  679. connection.execute(
  680. """INSERT INTO group_idempotency
  681. (request_id, operation, request_hash, response_json, created_at)
  682. VALUES (?, ?, ?, ?, ?)""",
  683. (
  684. canonical_request_id,
  685. operation,
  686. request_hash,
  687. response_json,
  688. self._now(),
  689. ),
  690. )
  691. return response
  692. except sqlite3.IntegrityError as error:
  693. raise self._integrity_conflict(error) from error
  694. def create_room(self, command: Mapping[str, object]) -> dict[str, object]:
  695. command = self._command(
  696. command, {"requestId", "name", "cwd", "maxReplyRounds", "agents"}
  697. )
  698. request_id = self._command_request_id(command)
  699. def action(connection: sqlite3.Connection) -> dict[str, object]:
  700. name = normalize_room_name(self._string(command, "name"))
  701. cwd = normalize_room_cwd(self._string(command, "cwd"))
  702. max_reply_rounds = normalize_max_reply_rounds(
  703. command.get("maxReplyRounds", DEFAULT_MAX_REPLY_ROUNDS)
  704. )
  705. agents = self._new_agents(command.get("agents"))
  706. now = self._now()
  707. room_id = str(uuid.uuid4())
  708. connection.execute(
  709. """INSERT INTO group_rooms
  710. (id, name, cwd, max_reply_rounds, created_at, updated_at, archived)
  711. VALUES (?, ?, ?, ?, ?, ?, 0)""",
  712. (room_id, name, cwd, max_reply_rounds, now, now),
  713. )
  714. for agent in agents:
  715. self._insert_agent(connection, room_id, agent, now)
  716. room = self._room_detail(connection, room_id, include_archived=True)
  717. self._append_event(
  718. connection, room_id, "room.created", room, created_at=now
  719. )
  720. return room
  721. return self.execute_idempotent("room.created", request_id, command, action)
  722. def get_room(
  723. self, room_id: str, *, include_archived: bool = False
  724. ) -> dict[str, object]:
  725. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  726. with self.read_transaction() as connection:
  727. return self._room_detail(
  728. connection, canonical_room_id, include_archived=include_archived
  729. )
  730. def room_snapshot(self, room_id: str) -> dict[str, object]:
  731. """Read all state needed to recover one active room in one snapshot."""
  732. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  733. with self.read_transaction() as connection:
  734. result = self._room_detail(
  735. connection, canonical_room_id, include_archived=False
  736. )
  737. run_rows = connection.execute(
  738. """SELECT * FROM group_agent_runs
  739. WHERE room_id = ? AND status IN ('queued', 'running', 'awaiting_input')
  740. ORDER BY created_at ASC, id ASC""",
  741. (canonical_room_id,),
  742. ).fetchall()
  743. interaction_rows = connection.execute(
  744. """SELECT * FROM group_interactions
  745. WHERE room_id = ? AND status = 'pending'
  746. ORDER BY created_at ASC, id ASC""",
  747. (canonical_room_id,),
  748. ).fetchall()
  749. cursor_row = connection.execute(
  750. "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
  751. ).fetchone()
  752. status_priority = {
  753. "queued": 1,
  754. "running": 2,
  755. "awaiting_input": 3,
  756. }
  757. statuses: dict[str, str] = {}
  758. for run in run_rows:
  759. previous = statuses.get(run["agent_id"], "idle")
  760. if status_priority[run["status"]] > status_priority.get(previous, 0):
  761. statuses[run["agent_id"]] = run["status"]
  762. for agent in result["agents"]:
  763. agent["status"] = statuses.get(agent["id"], "idle")
  764. result["runs"] = [self._run_wire(row) for row in run_rows]
  765. result["pendingInteractions"] = [
  766. self._interaction_wire(row) for row in interaction_rows
  767. ]
  768. result["latestCursor"] = int(cursor_row["cursor"])
  769. return result
  770. def list_rooms(self, *, limit: int, cursor: str | None) -> CursorPage:
  771. if (
  772. not isinstance(limit, int)
  773. or isinstance(limit, bool)
  774. or not 1 <= limit <= 100
  775. ):
  776. raise ValueError("limit must be an integer from 1 to 100")
  777. cursor_values = self._decode_cursor(cursor) if cursor is not None else None
  778. query = """SELECT id, name, cwd, max_reply_rounds, created_at, updated_at, archived,
  779. (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id) AS agent_count
  780. FROM group_rooms WHERE archived = 0"""
  781. params: list[object] = []
  782. if cursor_values is not None:
  783. query += " AND ((updated_at < ?) OR (updated_at = ? AND id < ?))"
  784. params.extend((cursor_values[0], cursor_values[0], cursor_values[1]))
  785. query += " ORDER BY updated_at DESC, id DESC LIMIT ?"
  786. params.append(limit + 1)
  787. with self.connection() as connection:
  788. rows = connection.execute(query, params).fetchall()
  789. has_more = len(rows) > limit
  790. items = [self._room_summary(row) for row in rows[:limit]]
  791. next_cursor = None
  792. if has_more and items:
  793. last = rows[limit - 1]
  794. next_cursor = self._encode_cursor(last["updated_at"], last["id"])
  795. return CursorPage(items=items, next_cursor=next_cursor)
  796. def update_room(
  797. self, room_id: str, command: Mapping[str, object]
  798. ) -> dict[str, object]:
  799. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  800. command = self._command(
  801. command, {"requestId", "name", "cwd", "maxReplyRounds"}
  802. )
  803. request_id = self._command_request_id(command)
  804. changes = {
  805. key for key in ("name", "cwd", "maxReplyRounds") if key in command
  806. }
  807. if not changes:
  808. raise ValueError("Room update requires name, cwd, or maxReplyRounds")
  809. def action(connection: sqlite3.Connection) -> dict[str, object]:
  810. self._active_room(connection, canonical_room_id)
  811. values: list[object] = []
  812. assignments: list[str] = []
  813. if "name" in changes:
  814. assignments.append("name = ?")
  815. values.append(normalize_room_name(self._string(command, "name")))
  816. if "cwd" in changes:
  817. assignments.append("cwd = ?")
  818. values.append(normalize_room_cwd(self._string(command, "cwd")))
  819. if "maxReplyRounds" in changes:
  820. assignments.append("max_reply_rounds = ?")
  821. values.append(normalize_max_reply_rounds(command["maxReplyRounds"]))
  822. assignments.append("updated_at = ?")
  823. values.extend((self._now(), canonical_room_id))
  824. connection.execute(
  825. f"UPDATE group_rooms SET {', '.join(assignments)} WHERE id = ?", values
  826. )
  827. model_changes = changes & {"model", "provider"}
  828. if model_changes and model_changes != {"model", "provider"}:
  829. raise ValueError("model and provider must be updated together")
  830. if model_changes and ((command["model"] is None) != (command["provider"] is None)):
  831. raise ValueError("model and provider must both be set or both be null")
  832. room = self._room_detail(
  833. connection, canonical_room_id, include_archived=True
  834. )
  835. self._append_event(connection, canonical_room_id, "room.updated", room)
  836. return room
  837. return self.execute_idempotent(
  838. "room.updated",
  839. request_id,
  840. self._scoped_payload(command, canonical_room_id),
  841. action,
  842. )
  843. def archive_room(
  844. self, room_id: str, command: Mapping[str, object]
  845. ) -> dict[str, object]:
  846. return self.archive_room_with_runtime_targets(room_id, command)["result"]
  847. def archive_room_with_runtime_targets(
  848. self, room_id: str, command: Mapping[str, object]
  849. ) -> dict[str, object]:
  850. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  851. command = self._command(command, {"requestId"})
  852. request_id = self._command_request_id(command)
  853. def action(connection: sqlite3.Connection) -> dict[str, object]:
  854. self._active_room(connection, canonical_room_id)
  855. now = self._now()
  856. interrupted = self._interrupt_runs_for_scope(
  857. connection,
  858. room_id=canonical_room_id,
  859. reason="Room archived",
  860. now=now,
  861. )
  862. connection.execute(
  863. "UPDATE group_rooms SET archived = 1, updated_at = ? WHERE id = ?",
  864. (now, canonical_room_id),
  865. )
  866. room = self._room_detail(
  867. connection, canonical_room_id, include_archived=True
  868. )
  869. self._append_event(
  870. connection, canonical_room_id, "room.deleted", room, created_at=now
  871. )
  872. return {
  873. "result": room,
  874. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  875. }
  876. response = self.execute_idempotent(
  877. "room.deleted",
  878. request_id,
  879. self._scoped_payload(command, canonical_room_id),
  880. action,
  881. )
  882. return self._runtime_envelope(response)
  883. def add_agent(
  884. self, room_id: str, command: Mapping[str, object]
  885. ) -> dict[str, object]:
  886. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  887. command = self._command(
  888. command,
  889. {
  890. "requestId",
  891. "profile",
  892. "displayName",
  893. "description",
  894. "replyWithoutMention",
  895. "model",
  896. "provider",
  897. "reasoningEffort",
  898. "fastMode",
  899. },
  900. )
  901. request_id = self._command_request_id(command)
  902. def action(connection: sqlite3.Connection) -> dict[str, object]:
  903. self._active_room(connection, canonical_room_id)
  904. count = connection.execute(
  905. "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
  906. (canonical_room_id,),
  907. ).fetchone()[0]
  908. if count >= MAX_AGENTS_PER_ROOM:
  909. raise GroupConflictError(
  910. "Room has reached the maximum number of agents"
  911. )
  912. agent = self._new_agent(
  913. {
  914. key: command[key]
  915. for key in (
  916. "profile",
  917. "displayName",
  918. "description",
  919. "replyWithoutMention",
  920. "model",
  921. "provider",
  922. "reasoningEffort",
  923. "fastMode",
  924. )
  925. if key in command
  926. }
  927. )
  928. now = self._now()
  929. agent_id = self._insert_agent(connection, canonical_room_id, agent, now)
  930. result = self._agent_detail(connection, canonical_room_id, agent_id)
  931. connection.execute(
  932. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  933. (now, canonical_room_id),
  934. )
  935. self._append_event(connection, canonical_room_id, "agent.created", result)
  936. self._append_room_updated_summary(
  937. connection, canonical_room_id, created_at=now
  938. )
  939. return result
  940. return self.execute_idempotent(
  941. "agent.created",
  942. request_id,
  943. self._scoped_payload(command, canonical_room_id),
  944. action,
  945. )
  946. def update_agent(
  947. self, room_id: str, agent_id: str, command: Mapping[str, object]
  948. ) -> dict[str, object]:
  949. return self.update_agent_with_runtime_targets(room_id, agent_id, command)[
  950. "result"
  951. ]
  952. def update_agent_with_runtime_targets(
  953. self, room_id: str, agent_id: str, command: Mapping[str, object]
  954. ) -> dict[str, object]:
  955. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  956. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  957. command = self._command(
  958. command,
  959. {
  960. "requestId",
  961. "displayName",
  962. "description",
  963. "enabled",
  964. "replyWithoutMention",
  965. "model",
  966. "provider",
  967. "reasoningEffort",
  968. "fastMode",
  969. },
  970. )
  971. request_id = self._command_request_id(command)
  972. changes = {
  973. key
  974. for key in (
  975. "displayName",
  976. "description",
  977. "enabled",
  978. "replyWithoutMention",
  979. "model",
  980. "provider",
  981. "reasoningEffort",
  982. "fastMode",
  983. )
  984. if key in command
  985. }
  986. if not changes:
  987. raise ValueError(
  988. "Agent update requires a mutable agent field"
  989. )
  990. def action(connection: sqlite3.Connection) -> dict[str, object]:
  991. self._active_room(connection, canonical_room_id)
  992. previous = self._owned_agent(
  993. connection, canonical_room_id, canonical_agent_id
  994. )
  995. assignments: list[str] = []
  996. values: list[object] = []
  997. if "displayName" in changes:
  998. raw_name = command.get("displayName")
  999. configured = self._resolved_agent_name(previous["profile"])
  1000. effective = (
  1001. raw_name.strip()
  1002. if isinstance(raw_name, str) and raw_name.strip()
  1003. else configured or previous["profile"]
  1004. )
  1005. display_name, display_key = normalize_display_name(effective)
  1006. self._check_agent_conflicts(
  1007. connection,
  1008. canonical_room_id,
  1009. display_key,
  1010. exclude_agent_id=canonical_agent_id,
  1011. )
  1012. assignments.extend(("display_name = ?", "display_name_key = ?"))
  1013. values.extend((display_name, display_key))
  1014. if "description" in changes:
  1015. assignments.append("description = ?")
  1016. values.append(self._description(command.get("description")))
  1017. if "enabled" in changes:
  1018. enabled = command["enabled"]
  1019. if not isinstance(enabled, bool):
  1020. raise ValueError("enabled must be a boolean")
  1021. assignments.append("enabled = ?")
  1022. values.append(int(enabled))
  1023. if "replyWithoutMention" in changes:
  1024. reply_without_mention = command["replyWithoutMention"]
  1025. if not isinstance(reply_without_mention, bool):
  1026. raise ValueError("replyWithoutMention must be a boolean")
  1027. assignments.append("reply_without_mention = ?")
  1028. values.append(int(reply_without_mention))
  1029. configuration_columns = {
  1030. "model": "model_override",
  1031. "provider": "provider_override",
  1032. "reasoningEffort": "reasoning_effort_override",
  1033. }
  1034. for key, column in configuration_columns.items():
  1035. if key in changes:
  1036. assignments.append(f"{column} = ?")
  1037. values.append(self._agent_configuration_value(command[key], key))
  1038. if "fastMode" in changes:
  1039. fast_mode = command["fastMode"]
  1040. if fast_mode is not None and not isinstance(fast_mode, bool):
  1041. raise ValueError("fastMode must be a boolean or null")
  1042. assignments.append("fast_mode_override = ?")
  1043. values.append(None if fast_mode is None else int(fast_mode))
  1044. if changes & {"model", "provider", "reasoningEffort", "fastMode"}:
  1045. # The active run keeps its current session. The next scheduler
  1046. # pass sees this stale marker and rotates before submitting.
  1047. assignments.append("session_config_json = NULL")
  1048. now = self._now()
  1049. interrupted = {"runIds": [], "runtimeSessionIds": []}
  1050. if (
  1051. "enabled" in changes
  1052. and bool(previous["enabled"])
  1053. and command["enabled"] is False
  1054. ):
  1055. interrupted = self._interrupt_runs_for_scope(
  1056. connection,
  1057. room_id=canonical_room_id,
  1058. agent_id=canonical_agent_id,
  1059. reason="Agent disabled",
  1060. now=now,
  1061. )
  1062. assignments.append("updated_at = ?")
  1063. values.extend((now, canonical_agent_id, canonical_room_id))
  1064. connection.execute(
  1065. f"UPDATE group_agents SET {', '.join(assignments)} WHERE id = ? AND room_id = ?",
  1066. values,
  1067. )
  1068. connection.execute(
  1069. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  1070. (now, canonical_room_id),
  1071. )
  1072. result = self._agent_detail(
  1073. connection, canonical_room_id, canonical_agent_id
  1074. )
  1075. self._append_event(connection, canonical_room_id, "agent.updated", result)
  1076. self._append_room_updated_summary(
  1077. connection, canonical_room_id, created_at=now
  1078. )
  1079. if interrupted["runIds"]:
  1080. self._append_agent_status(
  1081. connection, canonical_room_id, canonical_agent_id, now
  1082. )
  1083. return {
  1084. "result": result,
  1085. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  1086. }
  1087. response = self.execute_idempotent(
  1088. "agent.updated",
  1089. request_id,
  1090. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  1091. action,
  1092. )
  1093. return self._runtime_envelope(response)
  1094. def delete_agent(
  1095. self, room_id: str, agent_id: str, command: Mapping[str, object]
  1096. ) -> dict[str, object]:
  1097. return self.delete_agent_with_runtime_targets(room_id, agent_id, command)[
  1098. "result"
  1099. ]
  1100. def delete_agent_with_runtime_targets(
  1101. self, room_id: str, agent_id: str, command: Mapping[str, object]
  1102. ) -> dict[str, object]:
  1103. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1104. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  1105. command = self._command(command, {"requestId"})
  1106. request_id = self._command_request_id(command)
  1107. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1108. self._active_room(connection, canonical_room_id)
  1109. result = self._agent_detail(
  1110. connection, canonical_room_id, canonical_agent_id
  1111. )
  1112. agent_count = connection.execute(
  1113. "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
  1114. (canonical_room_id,),
  1115. ).fetchone()[0]
  1116. if agent_count <= 1:
  1117. raise GroupConflictError("Room must retain at least one agent")
  1118. now = self._now()
  1119. interrupted = self._interrupt_runs_for_scope(
  1120. connection,
  1121. room_id=canonical_room_id,
  1122. agent_id=canonical_agent_id,
  1123. reason="Agent removed",
  1124. now=now,
  1125. )
  1126. connection.execute(
  1127. "DELETE FROM group_agents WHERE id = ? AND room_id = ?",
  1128. (canonical_agent_id, canonical_room_id),
  1129. )
  1130. connection.execute(
  1131. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  1132. (now, canonical_room_id),
  1133. )
  1134. self._append_event(
  1135. connection, canonical_room_id, "agent.deleted", result, created_at=now
  1136. )
  1137. self._append_room_updated_summary(
  1138. connection, canonical_room_id, created_at=now
  1139. )
  1140. return {
  1141. "result": result,
  1142. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  1143. }
  1144. response = self.execute_idempotent(
  1145. "agent.deleted",
  1146. request_id,
  1147. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  1148. action,
  1149. )
  1150. return self._runtime_envelope(response)
  1151. def interrupt_agent_with_runtime_targets(
  1152. self, room_id: str, agent_id: str, command: Mapping[str, object]
  1153. ) -> dict[str, object]:
  1154. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1155. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  1156. command = self._command(command, {"requestId"})
  1157. request_id = self._command_request_id(command)
  1158. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1159. self._active_room(connection, canonical_room_id)
  1160. self._owned_agent(connection, canonical_room_id, canonical_agent_id)
  1161. now = self._now()
  1162. interrupted = self._interrupt_runs_for_scope(
  1163. connection,
  1164. room_id=canonical_room_id,
  1165. agent_id=canonical_agent_id,
  1166. reason="Agent interrupted",
  1167. now=now,
  1168. include_queued=False,
  1169. )
  1170. if interrupted["runIds"]:
  1171. self._append_agent_status(
  1172. connection, canonical_room_id, canonical_agent_id, now
  1173. )
  1174. return {
  1175. "result": {
  1176. "roomId": canonical_room_id,
  1177. "agentId": canonical_agent_id,
  1178. "interruptedRunIds": interrupted["runIds"],
  1179. },
  1180. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  1181. }
  1182. response = self.execute_idempotent(
  1183. "agent.interrupted",
  1184. request_id,
  1185. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  1186. action,
  1187. )
  1188. return self._runtime_envelope(response)
  1189. def create_human_message(
  1190. self,
  1191. room_id: str,
  1192. *,
  1193. request_id: str,
  1194. client_message_id: str,
  1195. content: str,
  1196. mention_agent_ids: object,
  1197. ) -> dict[str, object]:
  1198. """Persist one human turn and the deterministic agent work it starts."""
  1199. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1200. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  1201. canonical_client_id = self._canonical_uuid(client_message_id, "clientMessageId")
  1202. message_content = self._message_text(
  1203. content, "content", max_bytes=MAX_MESSAGE_BYTES, nonblank=True
  1204. )
  1205. agent_ids = self._mention_agent_ids(mention_agent_ids)
  1206. payload = {
  1207. "roomId": canonical_room_id,
  1208. "clientMessageId": canonical_client_id,
  1209. "content": message_content,
  1210. "mentionAgentIds": agent_ids,
  1211. }
  1212. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1213. self._active_room(connection, canonical_room_id)
  1214. agents: list[tuple[sqlite3.Row, str]] = []
  1215. room_agents = connection.execute(
  1216. """SELECT * FROM group_agents WHERE room_id = ?
  1217. ORDER BY created_at ASC, id ASC""",
  1218. (canonical_room_id,),
  1219. ).fetchall()
  1220. parsed_ids, _warnings = self._plan_cascade_mentions(
  1221. message_content,
  1222. room_agents,
  1223. source_agent_id="human",
  1224. include_automatic=False,
  1225. )
  1226. explicit_agent_ids = list(dict.fromkeys([*agent_ids, *parsed_ids]))
  1227. explicit_ids = set(explicit_agent_ids)
  1228. for agent_id in explicit_agent_ids:
  1229. agent = self._owned_agent(connection, canonical_room_id, agent_id)
  1230. if not agent["enabled"]:
  1231. raise GroupConflictError("Mentioned agent is disabled")
  1232. agents.append((agent, "mentioned"))
  1233. automatic_agents = [
  1234. agent
  1235. for agent in room_agents
  1236. if agent["enabled"] and agent["reply_without_mention"]
  1237. ]
  1238. agents.extend(
  1239. (agent, "automatic")
  1240. for agent in automatic_agents
  1241. if agent["id"] not in explicit_ids
  1242. )
  1243. now = self._now()
  1244. human_id = str(uuid.uuid4())
  1245. connection.execute(
  1246. """INSERT INTO group_messages
  1247. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  1248. reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
  1249. status, error, created_at, updated_at)
  1250. VALUES (?, ?, 'human', 'human', '你', ?, NULL, ?, ?, '', '[]', 'completed', '', ?, ?)""",
  1251. (
  1252. human_id,
  1253. canonical_room_id,
  1254. human_id,
  1255. canonical_client_id,
  1256. message_content,
  1257. now,
  1258. now,
  1259. ),
  1260. )
  1261. message = self._message_wire(self._message_row(connection, human_id))
  1262. self._append_event(
  1263. connection, canonical_room_id, "message.upsert", message, created_at=now
  1264. )
  1265. runs: list[dict[str, object]] = []
  1266. for agent, reply_mode in agents:
  1267. visible = reply_mode == "mentioned"
  1268. response_id, run_id = str(uuid.uuid4()), str(uuid.uuid4())
  1269. connection.execute(
  1270. """INSERT INTO group_messages
  1271. (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
  1272. reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
  1273. status, error, visible, created_at, updated_at)
  1274. VALUES (?, ?, 'agent', ?, ?, ?, ?, NULL, '', '', '[]', 'queued', '', ?, ?, ?)""",
  1275. (
  1276. response_id,
  1277. canonical_room_id,
  1278. agent["id"],
  1279. agent["display_name"],
  1280. human_id,
  1281. human_id,
  1282. int(visible),
  1283. now,
  1284. now,
  1285. ),
  1286. )
  1287. connection.execute(
  1288. """INSERT INTO group_agent_runs
  1289. (id, room_id, agent_id, trigger_message_id, response_message_id, root_message_id,
  1290. depth, reply_mode, status, runtime_session_id, error, created_at, updated_at)
  1291. VALUES (?, ?, ?, ?, ?, ?, 0, ?, 'queued', NULL, '', ?, ?)""",
  1292. (
  1293. run_id,
  1294. canonical_room_id,
  1295. agent["id"],
  1296. human_id,
  1297. response_id,
  1298. human_id,
  1299. reply_mode,
  1300. now,
  1301. now,
  1302. ),
  1303. )
  1304. response = self._message_wire(
  1305. self._message_row(connection, response_id)
  1306. )
  1307. run = self._run_wire(self._run_row(connection, run_id))
  1308. if visible:
  1309. self._append_event(
  1310. connection,
  1311. canonical_room_id,
  1312. "message.upsert",
  1313. response,
  1314. created_at=now,
  1315. )
  1316. self._append_event(
  1317. connection, canonical_room_id, "run.updated", run, created_at=now
  1318. )
  1319. runs.append(run)
  1320. return {"message": message, "runs": runs}
  1321. try:
  1322. return self.execute_idempotent(
  1323. "message.create", canonical_request_id, payload, action
  1324. )
  1325. except sqlite3.IntegrityError as error:
  1326. raise self._integrity_conflict(error) from error
  1327. def get_message(self, message_id: str) -> dict[str, object]:
  1328. canonical_message_id = self._canonical_uuid(message_id, "messageId")
  1329. with self.read_transaction() as connection:
  1330. return self._message_wire(
  1331. self._message_row(connection, canonical_message_id)
  1332. )
  1333. def get_run(self, run_id: str) -> dict[str, object]:
  1334. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1335. with self.read_transaction() as connection:
  1336. return self._run_wire(self._run_row(connection, canonical_run_id))
  1337. def get_interaction(self, interaction_id: str) -> dict[str, object]:
  1338. canonical_interaction_id = self._interaction_id(interaction_id)
  1339. with self.read_transaction() as connection:
  1340. return self._interaction_wire(
  1341. self._interaction_row(connection, canonical_interaction_id)
  1342. )
  1343. def list_messages(
  1344. self,
  1345. room_id: str,
  1346. *,
  1347. before_seq: int | None = None,
  1348. after_seq: int | None = None,
  1349. limit: int = MAX_MESSAGE_PAGE_SIZE,
  1350. ) -> list[dict[str, object]]:
  1351. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1352. self._page_limit(limit, MAX_MESSAGE_PAGE_SIZE, "limit")
  1353. if before_seq is not None and after_seq is not None:
  1354. raise ValueError("before_seq and after_seq are mutually exclusive")
  1355. before = (
  1356. self._positive_int(before_seq, "before_seq")
  1357. if before_seq is not None
  1358. else None
  1359. )
  1360. after = (
  1361. self._positive_int(after_seq, "after_seq")
  1362. if after_seq is not None
  1363. else None
  1364. )
  1365. with self.read_transaction() as connection:
  1366. self._room_detail(connection, canonical_room_id, include_archived=True)
  1367. if before is not None:
  1368. rows = connection.execute(
  1369. "SELECT * FROM group_messages WHERE room_id = ? AND visible = 1 AND seq < ? ORDER BY seq DESC LIMIT ?",
  1370. (canonical_room_id, before, limit),
  1371. ).fetchall()
  1372. rows = list(reversed(rows))
  1373. elif after is not None:
  1374. rows = connection.execute(
  1375. "SELECT * FROM group_messages WHERE room_id = ? AND visible = 1 AND seq > ? ORDER BY seq ASC LIMIT ?",
  1376. (canonical_room_id, after, limit),
  1377. ).fetchall()
  1378. else:
  1379. rows = connection.execute(
  1380. "SELECT * FROM group_messages WHERE room_id = ? AND visible = 1 ORDER BY seq DESC LIMIT ?",
  1381. (canonical_room_id, limit),
  1382. ).fetchall()
  1383. rows = list(reversed(rows))
  1384. return [self._message_wire(row) for row in rows]
  1385. def claim_next_runnable_run(self) -> dict[str, object] | None:
  1386. """Atomically claim the oldest eligible queued run."""
  1387. with self.write_transaction() as connection:
  1388. active_count = int(
  1389. connection.execute(
  1390. """SELECT COUNT(*) FROM group_agent_runs
  1391. WHERE status IN ('running', 'awaiting_input')"""
  1392. ).fetchone()[0]
  1393. )
  1394. if active_count >= MAX_PLUGIN_CONCURRENCY:
  1395. return None
  1396. run = connection.execute(
  1397. """SELECT candidate.* FROM group_agent_runs AS candidate
  1398. JOIN group_rooms AS room ON room.id = candidate.room_id
  1399. JOIN group_agents AS agent
  1400. ON agent.id = candidate.agent_id
  1401. AND agent.room_id = candidate.room_id
  1402. JOIN group_messages AS trigger_message
  1403. ON trigger_message.id = candidate.trigger_message_id
  1404. WHERE candidate.status = 'queued'
  1405. AND room.archived = 0
  1406. AND agent.enabled = 1
  1407. AND NOT EXISTS (
  1408. SELECT 1 FROM group_agent_runs AS occupied_agent
  1409. WHERE occupied_agent.agent_id = candidate.agent_id
  1410. AND occupied_agent.status IN ('running', 'awaiting_input')
  1411. )
  1412. AND (
  1413. SELECT COUNT(*) FROM group_agent_runs AS occupied_room
  1414. WHERE occupied_room.room_id = candidate.room_id
  1415. AND occupied_room.status IN ('running', 'awaiting_input')
  1416. ) < ?
  1417. ORDER BY trigger_message.seq ASC,
  1418. candidate.created_at ASC,
  1419. candidate.id ASC
  1420. LIMIT 1""",
  1421. (MAX_ROOM_CONCURRENCY,),
  1422. ).fetchone()
  1423. if run is None:
  1424. return None
  1425. response = self._message_row(connection, run["response_message_id"])
  1426. self._validate_run_message_state(run, response)
  1427. now = self._now()
  1428. result = self._update_run(connection, run, "running", now, UNSET, UNSET)
  1429. self._append_event(
  1430. connection,
  1431. run["room_id"],
  1432. "run.updated",
  1433. result,
  1434. created_at=now,
  1435. )
  1436. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  1437. return result
  1438. def read_run_projection(self, run_id: str) -> dict[str, object]:
  1439. """Return a stable, bounded context projection for one claimed run."""
  1440. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1441. with self.read_transaction() as connection:
  1442. run = self._run_row(connection, canonical_run_id)
  1443. if run["status"] not in {"running", "awaiting_input"}:
  1444. raise GroupConflictError("Run is not claimed")
  1445. room = self._active_room(connection, run["room_id"])
  1446. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  1447. trigger = self._message_row(connection, run["trigger_message_id"])
  1448. if trigger["room_id"] != run["room_id"]:
  1449. raise GroupStoreError("Run trigger message is corrupt")
  1450. lower_seq = int(agent["last_context_message_seq"])
  1451. trigger_seq = int(trigger["seq"])
  1452. through_seq = self._safe_context_seq(
  1453. connection, run["room_id"], lower_seq, trigger_seq
  1454. )
  1455. eligibility = """FROM group_messages
  1456. WHERE room_id = ? AND seq > ? AND seq <= ?
  1457. AND visible = 1
  1458. AND status IN ('completed', 'failed', 'interrupted')
  1459. AND NOT (sender_kind = 'agent' AND sender_id = ?)"""
  1460. parameters = (
  1461. run["room_id"],
  1462. lower_seq,
  1463. trigger_seq,
  1464. run["agent_id"],
  1465. )
  1466. total = int(
  1467. connection.execute(
  1468. f"SELECT COUNT(*) {eligibility}", parameters
  1469. ).fetchone()[0]
  1470. )
  1471. rows = connection.execute(
  1472. f"""SELECT * {eligibility}
  1473. ORDER BY seq DESC LIMIT ?""",
  1474. (*parameters, INITIAL_CONTEXT_MESSAGE_LIMIT),
  1475. ).fetchall()
  1476. rows = list(reversed(rows))
  1477. omitted = total - len(rows)
  1478. omitted_through_seq: int | None = None
  1479. if omitted:
  1480. omitted_through_seq = int(
  1481. connection.execute(
  1482. f"""SELECT MAX(seq) {eligibility}
  1483. AND seq < ?""",
  1484. (*parameters, rows[0]["seq"]),
  1485. ).fetchone()[0]
  1486. )
  1487. initial = agent["stored_session_id"] is None
  1488. messages = [self._projection_message(row) for row in rows]
  1489. messages, omitted, omitted_through_seq, omitted_summary = (
  1490. self._bound_projection_messages(
  1491. messages,
  1492. omitted_count=omitted,
  1493. omitted_through_seq=omitted_through_seq,
  1494. )
  1495. )
  1496. return {
  1497. "run": self._run_wire(run),
  1498. "room": self._room_wire(room),
  1499. "agent": self._agent_wire(agent),
  1500. "messages": messages,
  1501. "initial": initial,
  1502. "triggerSeq": trigger_seq,
  1503. "throughSeq": through_seq,
  1504. "omittedMessageCount": omitted,
  1505. "omittedThroughSeq": omitted_through_seq,
  1506. "omittedSummary": omitted_summary,
  1507. "characterBudget": CONTEXT_CHARACTER_BUDGET,
  1508. }
  1509. def bind_run_session(
  1510. self,
  1511. run_id: str,
  1512. *,
  1513. expected_stored_session_id: str | None,
  1514. stored_session_id: str,
  1515. runtime_session_id: str,
  1516. ) -> dict[str, object]:
  1517. """CAS-bind stored and runtime identities for the current generation."""
  1518. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1519. expected_stored = self._runtime_session_id(expected_stored_session_id)
  1520. stored = self._runtime_session_id(stored_session_id)
  1521. runtime = self._runtime_session_id(runtime_session_id)
  1522. if stored is None:
  1523. raise ValueError("storedSessionId is invalid")
  1524. if runtime is None:
  1525. raise ValueError("runtimeSessionId is invalid")
  1526. with self.write_transaction() as connection:
  1527. run = self._run_row(connection, canonical_run_id)
  1528. self._active_room(connection, run["room_id"])
  1529. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  1530. response = self._message_row(connection, run["response_message_id"])
  1531. self._validate_run_message_state(run, response)
  1532. if run["status"] not in {"running", "awaiting_input"}:
  1533. raise GroupConflictError("Run does not accept a session binding")
  1534. if agent["stored_session_id"] != expected_stored:
  1535. raise GroupConflictError("stored session generation changed")
  1536. if run["runtime_session_id"] not in {None, runtime}:
  1537. raise GroupConflictError("Run runtime is already bound")
  1538. self._require_available_runtime(connection, runtime, canonical_run_id)
  1539. now = self._now()
  1540. if agent["stored_session_id"] != stored:
  1541. connection.execute(
  1542. """UPDATE group_agents
  1543. SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
  1544. (stored, now, agent["id"]),
  1545. )
  1546. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  1547. self._append_event(
  1548. connection,
  1549. run["room_id"],
  1550. "agent.updated",
  1551. self._agent_wire(agent),
  1552. created_at=now,
  1553. )
  1554. if run["runtime_session_id"] != runtime:
  1555. changed = self._update_run(
  1556. connection, run, run["status"], now, runtime, UNSET
  1557. )
  1558. self._append_event(
  1559. connection,
  1560. run["room_id"],
  1561. "run.updated",
  1562. changed,
  1563. created_at=now,
  1564. )
  1565. else:
  1566. changed = self._run_wire(run)
  1567. return {"run": changed, "agent": self._agent_wire(agent)}
  1568. def advance_run_context(
  1569. self,
  1570. run_id: str,
  1571. *,
  1572. runtime_session_id: str,
  1573. expected_context_seq: int,
  1574. through_seq: int,
  1575. ) -> dict[str, object]:
  1576. """Advance one Agent context watermark with generation and hole CAS checks."""
  1577. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1578. runtime = self._runtime_session_id(runtime_session_id)
  1579. if runtime is None:
  1580. raise ValueError("runtimeSessionId is invalid")
  1581. expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
  1582. through = self._nonnegative_int(through_seq, "throughSeq")
  1583. with self.write_transaction() as connection:
  1584. run = self._run_row(connection, canonical_run_id)
  1585. self._active_room(connection, run["room_id"])
  1586. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  1587. if run["status"] not in {"running", "awaiting_input"}:
  1588. raise GroupConflictError("Run no longer accepts context")
  1589. if run["runtime_session_id"] != runtime:
  1590. raise GroupConflictError("Run runtime generation changed")
  1591. if int(agent["last_context_message_seq"]) != expected:
  1592. raise GroupConflictError("Agent context generation changed")
  1593. trigger = self._message_row(connection, run["trigger_message_id"])
  1594. safe = self._safe_context_seq(
  1595. connection, run["room_id"], expected, int(trigger["seq"])
  1596. )
  1597. if through < expected or through > safe:
  1598. raise GroupConflictError("throughSeq exceeds safe projection")
  1599. now = self._now()
  1600. connection.execute(
  1601. """UPDATE group_agents
  1602. SET last_context_message_seq = ?, updated_at = ? WHERE id = ?""",
  1603. (through, now, agent["id"]),
  1604. )
  1605. changed = self._agent_wire(
  1606. self._owned_agent(connection, run["room_id"], run["agent_id"])
  1607. )
  1608. self._append_event(
  1609. connection,
  1610. run["room_id"],
  1611. "agent.updated",
  1612. changed,
  1613. created_at=now,
  1614. )
  1615. return changed
  1616. def commit_prompt_submission(
  1617. self,
  1618. run_id: str,
  1619. *,
  1620. expected_stored_session_id: str | None,
  1621. stored_session_id: str,
  1622. runtime_session_id: str,
  1623. expected_context_seq: int,
  1624. through_seq: int,
  1625. ) -> dict[str, object]:
  1626. """Commit a successful prompt submission and its durable context CAS."""
  1627. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1628. expected_stored = self._runtime_session_id(expected_stored_session_id)
  1629. stored = self._runtime_session_id(stored_session_id)
  1630. runtime = self._runtime_session_id(runtime_session_id)
  1631. expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
  1632. through = self._nonnegative_int(through_seq, "throughSeq")
  1633. if stored is None:
  1634. raise ValueError("storedSessionId is invalid")
  1635. if runtime is None:
  1636. raise ValueError("runtimeSessionId is invalid")
  1637. operation = f"run.prompt.submitted:{canonical_run_id}"
  1638. legacy_ledger_id = str(
  1639. uuid.uuid5(
  1640. uuid.NAMESPACE_URL,
  1641. f"hermes://yaoyao-group/{canonical_run_id}/prompt-submission",
  1642. )
  1643. )
  1644. ledger_id = f"internal:prompt:{canonical_run_id}"
  1645. payload = {
  1646. "runId": canonical_run_id,
  1647. "expectedStoredSessionId": expected_stored,
  1648. "storedSessionId": stored,
  1649. "runtimeSessionId": runtime,
  1650. "expectedContextSeq": expected,
  1651. "throughSeq": through,
  1652. }
  1653. request_hash = hashlib.sha256(
  1654. self._canonical_json(payload).encode()
  1655. ).hexdigest()
  1656. with self.write_transaction() as connection:
  1657. run = self._run_row(connection, canonical_run_id)
  1658. self._active_room(connection, run["room_id"])
  1659. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  1660. response = self._message_row(connection, run["response_message_id"])
  1661. self._validate_run_message_state(run, response)
  1662. if run["status"] != "running":
  1663. raise GroupConflictError("Run no longer accepts a prompt submission")
  1664. if run["runtime_session_id"] != runtime:
  1665. raise GroupConflictError("Run runtime generation changed")
  1666. current_stored = agent["stored_session_id"]
  1667. current_context = int(agent["last_context_message_seq"])
  1668. existing = connection.execute(
  1669. """SELECT request_id, operation, request_hash, response_json
  1670. FROM group_idempotency WHERE request_id = ?""",
  1671. (ledger_id,),
  1672. ).fetchone()
  1673. legacy_existing = None
  1674. if existing is None:
  1675. candidate = connection.execute(
  1676. """SELECT operation, request_hash, response_json
  1677. FROM group_idempotency WHERE request_id = ?""",
  1678. (legacy_ledger_id,),
  1679. ).fetchone()
  1680. if candidate is not None and candidate["operation"] == operation:
  1681. existing = candidate
  1682. legacy_existing = candidate
  1683. if existing is not None:
  1684. if (
  1685. existing["operation"] != operation
  1686. or existing["request_hash"] != request_hash
  1687. ):
  1688. raise GroupConflictError("Prompt submission generation changed")
  1689. if current_stored != stored or current_context != through:
  1690. raise GroupConflictError("Prompt submission generation changed")
  1691. stored_response = existing["response_json"]
  1692. try:
  1693. replay = self._load_json(stored_response)
  1694. except (TypeError, ValueError, json.JSONDecodeError) as error:
  1695. raise GroupStoreError(
  1696. "Stored prompt submission is corrupt"
  1697. ) from error
  1698. if (
  1699. not isinstance(replay, dict)
  1700. or self._canonical_json(replay) != stored_response
  1701. ):
  1702. raise GroupStoreError("Stored prompt submission is corrupt")
  1703. if legacy_existing is not None:
  1704. connection.execute(
  1705. """UPDATE group_idempotency SET request_id = ?
  1706. WHERE request_id = ?""",
  1707. (ledger_id, legacy_ledger_id),
  1708. )
  1709. return replay
  1710. if current_stored != expected_stored:
  1711. raise GroupConflictError("stored session generation changed")
  1712. if current_context != expected:
  1713. raise GroupConflictError("Agent context generation changed")
  1714. trigger = self._message_row(connection, run["trigger_message_id"])
  1715. safe = self._safe_context_seq(
  1716. connection, run["room_id"], expected, int(trigger["seq"])
  1717. )
  1718. if through < expected or through > safe:
  1719. raise GroupConflictError("throughSeq exceeds safe projection")
  1720. now = self._now()
  1721. if current_stored != stored or current_context != through:
  1722. connection.execute(
  1723. """UPDATE group_agents
  1724. SET stored_session_id = ?, last_context_message_seq = ?,
  1725. updated_at = ? WHERE id = ?""",
  1726. (stored, through, now, agent["id"]),
  1727. )
  1728. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  1729. self._append_event(
  1730. connection,
  1731. run["room_id"],
  1732. "agent.updated",
  1733. self._agent_wire(agent),
  1734. created_at=now,
  1735. )
  1736. result = {
  1737. "run": self._run_wire(run),
  1738. "agent": self._agent_wire(agent),
  1739. }
  1740. connection.execute(
  1741. """INSERT INTO group_idempotency
  1742. (request_id, operation, request_hash, response_json, created_at)
  1743. VALUES (?, ?, ?, ?, ?)""",
  1744. (
  1745. ledger_id,
  1746. operation,
  1747. request_hash,
  1748. self._canonical_json(result),
  1749. now,
  1750. ),
  1751. )
  1752. return result
  1753. def settle_run(
  1754. self,
  1755. run_id: str,
  1756. *,
  1757. runtime_session_id: str | None,
  1758. expected_stored_session_id: str | None,
  1759. stored_session_id: str | None,
  1760. outcome: str,
  1761. error: str = "",
  1762. ) -> dict[str, object]:
  1763. """Settle message, run, session rotation, and status in one transaction."""
  1764. canonical_run_id = self._canonical_uuid(run_id, "runId")
  1765. runtime = self._runtime_session_id(runtime_session_id)
  1766. expected_stored = self._runtime_session_id(expected_stored_session_id)
  1767. stored = self._runtime_session_id(stored_session_id)
  1768. run_error = self._message_text(error, "error", max_bytes=4096)
  1769. if outcome not in {"completed", "failed", "interrupted"}:
  1770. raise ValueError("outcome is invalid")
  1771. if runtime is None and outcome != "failed":
  1772. raise ValueError("A runtime-less settle only supports failed")
  1773. with self.write_transaction() as connection:
  1774. run = self._run_row(connection, canonical_run_id)
  1775. self._active_room(connection, run["room_id"])
  1776. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  1777. response = self._message_row(connection, run["response_message_id"])
  1778. self._validate_run_message_state(run, response)
  1779. if run["status"] not in {"running", "awaiting_input"}:
  1780. raise GroupConflictError("Run is already settled")
  1781. if run["runtime_session_id"] != runtime:
  1782. raise GroupConflictError("Run runtime generation changed")
  1783. if agent["stored_session_id"] != expected_stored:
  1784. raise GroupConflictError("stored session generation changed")
  1785. if outcome == "completed" and response["status"] != "completed":
  1786. raise GroupConflictError("Response message must be completed first")
  1787. now = self._now()
  1788. if stored != agent["stored_session_id"]:
  1789. connection.execute(
  1790. """UPDATE group_agents
  1791. SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
  1792. (stored, now, agent["id"]),
  1793. )
  1794. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  1795. self._append_event(
  1796. connection,
  1797. run["room_id"],
  1798. "agent.updated",
  1799. self._agent_wire(agent),
  1800. created_at=now,
  1801. )
  1802. self._cancel_pending_interactions(connection, run, now)
  1803. changed = self._update_run(connection, run, outcome, now, None, run_error)
  1804. self._fail_claimed_interaction_ledgers(
  1805. connection,
  1806. run_id=run["id"],
  1807. reason=run_error or f"Run {outcome}",
  1808. runtime_session_ids=[] if runtime is None else [runtime],
  1809. run=changed,
  1810. )
  1811. self._append_event(
  1812. connection,
  1813. run["room_id"],
  1814. "run.updated",
  1815. changed,
  1816. created_at=now,
  1817. )
  1818. if (
  1819. outcome in {"failed", "interrupted"}
  1820. and response["status"] != "completed"
  1821. ):
  1822. connection.execute(
  1823. """UPDATE group_messages
  1824. SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
  1825. (outcome, run_error, now, response["id"]),
  1826. )
  1827. response = self._message_row(connection, response["id"])
  1828. if response["visible"]:
  1829. self._append_event(
  1830. connection,
  1831. run["room_id"],
  1832. "message.upsert",
  1833. self._message_wire(response),
  1834. created_at=now,
  1835. )
  1836. if outcome == "completed":
  1837. self._record_cascade_plan(
  1838. connection,
  1839. source=run,
  1840. source_message=response,
  1841. created_at=now,
  1842. )
  1843. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  1844. return {
  1845. "run": changed,
  1846. "message": self._message_wire(response),
  1847. "agent": self._agent_wire(agent),
  1848. }
  1849. @classmethod
  1850. def _cascade_request_id(cls, source_run_id: str) -> str:
  1851. return f"internal:cascade:{source_run_id}"
  1852. @classmethod
  1853. def _cascade_request_hash(
  1854. cls, source_run_id: str, *, parse_version: int = _CASCADE_PARSE_VERSION
  1855. ) -> str:
  1856. payload = {
  1857. "parseVersion": parse_version,
  1858. "sourceRunId": source_run_id,
  1859. "version": 1,
  1860. }
  1861. return hashlib.sha256(cls._canonical_json(payload).encode()).hexdigest()
  1862. def _record_cascade_plan(
  1863. self,
  1864. connection: sqlite3.Connection,
  1865. *,
  1866. source: sqlite3.Row,
  1867. source_message: sqlite3.Row,
  1868. created_at: float,
  1869. ) -> None:
  1870. request_id = self._cascade_request_id(source["id"])
  1871. existing = connection.execute(
  1872. "SELECT 1 FROM group_idempotency WHERE request_id = ?",
  1873. (request_id,),
  1874. ).fetchone()
  1875. if existing is not None:
  1876. raise GroupStoreError("Cascade ledger already exists")
  1877. agents = connection.execute(
  1878. "SELECT * FROM group_agents WHERE room_id = ? "
  1879. "ORDER BY created_at ASC, id ASC",
  1880. (source["room_id"],),
  1881. ).fetchall()
  1882. if source_message["visible"]:
  1883. target_ids, warnings = self._plan_cascade_mentions(
  1884. source_message["content"],
  1885. agents,
  1886. source_agent_id=source["agent_id"],
  1887. )
  1888. explicit_ids, _ = self._plan_cascade_mentions(
  1889. source_message["content"],
  1890. agents,
  1891. source_agent_id=source["agent_id"],
  1892. include_automatic=False,
  1893. )
  1894. else:
  1895. target_ids, warnings = [], []
  1896. explicit_ids = []
  1897. explicit_set = set(explicit_ids)
  1898. plan = {
  1899. "parseVersion": _CASCADE_PARSE_VERSION,
  1900. "sourceMessageId": source_message["id"],
  1901. "sourceRunId": source["id"],
  1902. "state": "pending",
  1903. "targets": [
  1904. {
  1905. "agentId": agent_id,
  1906. "replyMode": (
  1907. "mentioned" if agent_id in explicit_set else "automatic"
  1908. ),
  1909. }
  1910. for agent_id in target_ids
  1911. ],
  1912. "warnings": warnings,
  1913. "version": 1,
  1914. }
  1915. encoded = self._canonical_json(plan)
  1916. if len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES:
  1917. raise GroupStoreError("Cascade plan exceeds the internal limit")
  1918. connection.execute(
  1919. """INSERT INTO group_idempotency
  1920. (request_id, operation, request_hash, response_json, created_at)
  1921. VALUES (?, ?, ?, ?, ?)""",
  1922. (
  1923. request_id,
  1924. _CASCADE_PENDING_OPERATION,
  1925. self._cascade_request_hash(source["id"]),
  1926. encoded,
  1927. created_at,
  1928. ),
  1929. )
  1930. @classmethod
  1931. def _plan_cascade_mentions(
  1932. cls,
  1933. content: str,
  1934. agents: list[sqlite3.Row],
  1935. *,
  1936. source_agent_id: str,
  1937. include_automatic: bool = True,
  1938. ) -> tuple[list[str], list[dict[str, str]]]:
  1939. searchable = cls._mention_search_text(content)
  1940. entries: list[tuple[str, int, sqlite3.Row]] = []
  1941. for agent in agents:
  1942. aliases = (
  1943. (agent["id"], 0),
  1944. (agent["profile"], 1),
  1945. (agent["display_name"], 2),
  1946. )
  1947. seen: set[str] = set()
  1948. for alias, priority in aliases:
  1949. key = alias.casefold()
  1950. if key in seen or is_reserved_mention_alias(key):
  1951. continue
  1952. seen.add(key)
  1953. entries.append((key, priority, agent))
  1954. entries.sort(key=lambda item: (-len(item[0]), item[1], item[0], item[2]["id"]))
  1955. targets: list[str] = []
  1956. warning_names: list[str] = []
  1957. index = 0
  1958. while index < len(searchable):
  1959. if searchable[index] != "@" or (
  1960. index > 0 and cls._mention_word_char(searchable[index - 1])
  1961. ):
  1962. index += 1
  1963. continue
  1964. room_wide_match = next(
  1965. (
  1966. match
  1967. for alias in ALL_MENTION_ALIASES
  1968. if (match := cls._casefold_prefix(searchable, index + 1, alias))
  1969. is not None
  1970. and cls._mention_end(searchable, match)
  1971. ),
  1972. None,
  1973. )
  1974. if room_wide_match is not None:
  1975. for agent in agents:
  1976. if (
  1977. agent["enabled"]
  1978. and agent["id"] != source_agent_id
  1979. and agent["id"] not in targets
  1980. ):
  1981. targets.append(agent["id"])
  1982. index = room_wide_match
  1983. continue
  1984. matched = False
  1985. for key, _priority, agent in entries:
  1986. end = cls._casefold_prefix(searchable, index + 1, key)
  1987. if end is None or not cls._mention_end(searchable, end):
  1988. continue
  1989. matched = True
  1990. if not agent["enabled"]:
  1991. warning_names.append(f"Agent disabled: {agent['display_name']}")
  1992. elif agent["id"] != source_agent_id and agent["id"] not in targets:
  1993. targets.append(agent["id"])
  1994. index = end
  1995. break
  1996. if matched:
  1997. continue
  1998. token = re.match(
  1999. r"[^\s@,,。!?!?;;::()()\[\]{}]{1,100}",
  2000. searchable[index + 1 :],
  2001. )
  2002. if token is not None:
  2003. warning_names.append(f"Unknown Mention: @{token.group(0)}")
  2004. index += 1 + len(token.group(0))
  2005. else:
  2006. index += 1
  2007. if include_automatic:
  2008. for agent in agents:
  2009. if (
  2010. agent["enabled"]
  2011. and agent["reply_without_mention"]
  2012. and agent["id"] != source_agent_id
  2013. and agent["id"] not in targets
  2014. ):
  2015. targets.append(agent["id"])
  2016. warnings = [
  2017. {"code": "mention", "message": value}
  2018. for value in list(dict.fromkeys(warning_names))[:MAX_AGENTS_PER_ROOM]
  2019. ]
  2020. return targets[:MAX_AGENTS_PER_ROOM], warnings
  2021. @staticmethod
  2022. def _casefold_prefix(content: str, start: int, expected: str) -> int | None:
  2023. folded = ""
  2024. index = start
  2025. while index < len(content) and len(folded) < len(expected):
  2026. folded += content[index].casefold()
  2027. index += 1
  2028. return index if folded == expected else None
  2029. @staticmethod
  2030. def _mention_search_text(content: str) -> str:
  2031. lines = content.splitlines(keepends=True)
  2032. visible: list[str] = []
  2033. fence: tuple[str, int] | None = None
  2034. for line in lines:
  2035. leading_spaces = len(line) - len(line.lstrip(" "))
  2036. candidate = line[leading_spaces:] if leading_spaces <= 3 else ""
  2037. marker_character = (
  2038. candidate[0]
  2039. if candidate.startswith("`") or candidate.startswith("~")
  2040. else None
  2041. )
  2042. marker_length = 0
  2043. if marker_character is not None:
  2044. while (
  2045. marker_length < len(candidate)
  2046. and candidate[marker_length] == marker_character
  2047. ):
  2048. marker_length += 1
  2049. if fence is None and marker_length >= 3:
  2050. fence = (marker_character, marker_length)
  2051. continue
  2052. if fence is not None:
  2053. fence_character, fence_length = fence
  2054. remainder = candidate[marker_length:]
  2055. if (
  2056. marker_character == fence_character
  2057. and marker_length >= fence_length
  2058. and not remainder.strip()
  2059. ):
  2060. fence = None
  2061. continue
  2062. visible.append(line)
  2063. searchable = "".join(visible)
  2064. inline_visible: list[str] = []
  2065. for line in searchable.splitlines(keepends=True):
  2066. index = 0
  2067. while index < len(line):
  2068. if line[index] != "`":
  2069. inline_visible.append(line[index])
  2070. index += 1
  2071. continue
  2072. end = index + 1
  2073. while end < len(line) and line[end] == "`":
  2074. end += 1
  2075. delimiter = line[index:end]
  2076. close = line.find(delimiter, end)
  2077. if close < 0:
  2078. if line.endswith("\n"):
  2079. inline_visible.append("\n")
  2080. break
  2081. index = close + len(delimiter)
  2082. searchable = "".join(inline_visible)
  2083. searchable = re.sub(
  2084. r"(?:[A-Za-z][A-Za-z0-9+.-]*://|www\.)"
  2085. r"[^\s,。!?;:()()\[\]{}]+",
  2086. "",
  2087. searchable,
  2088. flags=re.IGNORECASE,
  2089. )
  2090. return re.sub(r"\\@", "", searchable)
  2091. @staticmethod
  2092. def _mention_word_char(value: str) -> bool:
  2093. return value.isalnum() or value in {"_", ".", "-", "+", "@"}
  2094. @classmethod
  2095. def _mention_end(cls, value: str, end: int) -> bool:
  2096. return end >= len(value) or not cls._mention_word_char(value[end])
  2097. def list_pending_cascades(
  2098. self, *, limit: int = _MAX_CASCADE_PAGE_SIZE, after: int | None = None
  2099. ) -> dict[str, object]:
  2100. if (
  2101. isinstance(limit, bool)
  2102. or not isinstance(limit, int)
  2103. or not (1 <= limit <= _MAX_CASCADE_PAGE_SIZE)
  2104. ):
  2105. raise ValueError("limit must be between 1 and 32")
  2106. if after is None:
  2107. after_value = 0
  2108. elif isinstance(after, bool) or not isinstance(after, int) or after < 0:
  2109. raise ValueError("after must be a non-negative integer")
  2110. else:
  2111. after_value = after
  2112. with self.read_transaction() as connection:
  2113. rows = connection.execute(
  2114. """SELECT rowid, request_id, operation, request_hash, response_json
  2115. FROM group_idempotency
  2116. WHERE operation = ? AND rowid > ?
  2117. ORDER BY rowid ASC LIMIT ?""",
  2118. (_CASCADE_PENDING_OPERATION, after_value, limit + 1),
  2119. ).fetchall()
  2120. validated = [
  2121. (int(row["rowid"]), self._cascade_plan_from_ledger(row)) for row in rows
  2122. ]
  2123. has_more = len(validated) > limit
  2124. validated = validated[:limit]
  2125. items = [{"sourceRunId": plan["sourceRunId"]} for _rowid, plan in validated]
  2126. return {
  2127. "items": items,
  2128. "nextCursor": (validated[-1][0] if has_more and validated else None),
  2129. }
  2130. def _cascade_plan_from_ledger(
  2131. self, ledger: Mapping[str, object]
  2132. ) -> dict[str, object]:
  2133. try:
  2134. request_id = ledger["request_id"]
  2135. operation = ledger["operation"]
  2136. request_hash = ledger["request_hash"]
  2137. encoded = ledger["response_json"]
  2138. except (KeyError, IndexError, TypeError) as error:
  2139. raise GroupStoreError("Stored cascade ledger is corrupt") from error
  2140. prefix = "internal:cascade:"
  2141. if (
  2142. not isinstance(request_id, str)
  2143. or not request_id.startswith(prefix)
  2144. or operation != _CASCADE_PENDING_OPERATION
  2145. or not isinstance(encoded, str)
  2146. or len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES
  2147. ):
  2148. raise GroupStoreError("Stored cascade ledger is corrupt")
  2149. raw_source_id = request_id[len(prefix) :]
  2150. try:
  2151. source_id = self._canonical_uuid(raw_source_id, "sourceRunId")
  2152. except ValueError as error:
  2153. raise GroupStoreError("Stored cascade ledger is corrupt") from error
  2154. if raw_source_id != source_id:
  2155. raise GroupStoreError("Stored cascade ledger is corrupt")
  2156. try:
  2157. plan = self._load_json(encoded)
  2158. except (TypeError, ValueError, json.JSONDecodeError) as error:
  2159. raise GroupStoreError("Stored cascade plan is corrupt") from error
  2160. if not isinstance(plan, dict) or self._canonical_json(plan) != encoded:
  2161. raise GroupStoreError("Stored cascade plan is corrupt")
  2162. parse_version = plan.get("parseVersion")
  2163. if (
  2164. parse_version not in {1, 2}
  2165. or request_hash
  2166. != self._cascade_request_hash(source_id, parse_version=parse_version)
  2167. ):
  2168. raise GroupStoreError("Stored cascade ledger is corrupt")
  2169. common_invalid = (
  2170. plan.get("state") != "pending"
  2171. or plan.get("version") != 1
  2172. or plan.get("sourceRunId") != source_id
  2173. or not isinstance(plan.get("warnings"), list)
  2174. or not all(isinstance(item, dict) for item in plan["warnings"])
  2175. or len(plan["warnings"]) > MAX_AGENTS_PER_ROOM
  2176. )
  2177. if common_invalid:
  2178. raise GroupStoreError("Stored cascade plan is corrupt")
  2179. if parse_version == 1:
  2180. expected_keys = {
  2181. "parseVersion",
  2182. "sourceMessageId",
  2183. "sourceRunId",
  2184. "state",
  2185. "targetAgentIds",
  2186. "version",
  2187. "warnings",
  2188. }
  2189. target_ids = plan.get("targetAgentIds")
  2190. if (
  2191. set(plan) != expected_keys
  2192. or not isinstance(target_ids, list)
  2193. or not all(isinstance(item, str) for item in target_ids)
  2194. ):
  2195. raise GroupStoreError("Stored cascade plan is corrupt")
  2196. targets = [
  2197. {"agentId": item, "replyMode": "mentioned"} for item in target_ids
  2198. ]
  2199. else:
  2200. expected_keys = {
  2201. "parseVersion",
  2202. "sourceMessageId",
  2203. "sourceRunId",
  2204. "state",
  2205. "targets",
  2206. "version",
  2207. "warnings",
  2208. }
  2209. targets = plan.get("targets")
  2210. if (
  2211. set(plan) != expected_keys
  2212. or not isinstance(targets, list)
  2213. or not all(isinstance(item, dict) for item in targets)
  2214. ):
  2215. raise GroupStoreError("Stored cascade plan is corrupt")
  2216. if (
  2217. len(targets) > MAX_AGENTS_PER_ROOM
  2218. or any(set(item) != {"agentId", "replyMode"} for item in targets)
  2219. or any(not isinstance(item.get("agentId"), str) for item in targets)
  2220. or any(item.get("replyMode") not in {"mentioned", "automatic"} for item in targets)
  2221. or len({item.get("agentId") for item in targets}) != len(targets)
  2222. ):
  2223. raise GroupStoreError("Stored cascade plan is corrupt")
  2224. try:
  2225. if (
  2226. self._canonical_uuid(plan["sourceMessageId"], "sourceMessageId")
  2227. != plan["sourceMessageId"]
  2228. ):
  2229. raise ValueError
  2230. for target in targets:
  2231. if (
  2232. self._canonical_uuid(target["agentId"], "targetAgentId")
  2233. != target["agentId"]
  2234. ):
  2235. raise ValueError
  2236. for warning in plan["warnings"]:
  2237. if set(warning) != {"code", "message"} or warning.get("code") != "mention":
  2238. raise ValueError
  2239. self._message_text(
  2240. warning.get("message"),
  2241. "warning.message",
  2242. max_bytes=MAX_MESSAGE_BYTES,
  2243. nonblank=True,
  2244. )
  2245. except (KeyError, TypeError, ValueError) as error:
  2246. raise GroupStoreError("Stored cascade plan is corrupt") from error
  2247. return {
  2248. "parseVersion": parse_version,
  2249. "sourceMessageId": plan["sourceMessageId"],
  2250. "sourceRunId": source_id,
  2251. "state": "pending",
  2252. "targets": targets,
  2253. "version": 1,
  2254. "warnings": plan["warnings"],
  2255. }
  2256. def enqueue_cascade_runs(
  2257. self,
  2258. source_run_id: str,
  2259. *,
  2260. agent_ids: list[str],
  2261. warnings: list[Mapping[str, object]],
  2262. ) -> dict[str, object]:
  2263. """Create bounded, deduplicated Agent cascades and visible warnings."""
  2264. canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
  2265. canonical_agent_ids, requested_warnings = self._validated_cascade_inputs(
  2266. agent_ids, warnings
  2267. )
  2268. with self.write_transaction() as connection:
  2269. source = self._run_row(connection, canonical_source_id)
  2270. self._active_room(connection, source["room_id"])
  2271. self._enabled_agent(connection, source["room_id"], source["agent_id"])
  2272. if source["status"] != "completed":
  2273. raise GroupConflictError("Cascade source run must be completed")
  2274. source_message = self._message_row(
  2275. connection, source["response_message_id"]
  2276. )
  2277. if source_message["status"] != "completed":
  2278. raise GroupConflictError("Cascade source message must be completed")
  2279. return self._enqueue_cascade_runs_transaction(
  2280. connection,
  2281. source=source,
  2282. canonical_agent_ids=canonical_agent_ids,
  2283. requested_warnings=requested_warnings,
  2284. now=self._now(),
  2285. )
  2286. def _validated_cascade_inputs(
  2287. self,
  2288. agent_ids: object,
  2289. warnings: object,
  2290. ) -> tuple[list[str], list[str]]:
  2291. if not isinstance(agent_ids, list):
  2292. raise ValueError("agent_ids must be a list")
  2293. if len(agent_ids) > MAX_AGENTS_PER_ROOM:
  2294. raise ValueError(
  2295. f"agent_ids must contain at most {MAX_AGENTS_PER_ROOM} entries"
  2296. )
  2297. canonical_agent_ids: list[str] = []
  2298. seen_agent_ids: set[str] = set()
  2299. for value in agent_ids:
  2300. agent_id = self._canonical_uuid(value, "agentId")
  2301. if agent_id not in seen_agent_ids:
  2302. seen_agent_ids.add(agent_id)
  2303. canonical_agent_ids.append(agent_id)
  2304. if not isinstance(warnings, list):
  2305. raise ValueError("warnings must be a list of objects")
  2306. if len(warnings) > MAX_AGENTS_PER_ROOM:
  2307. raise ValueError(
  2308. f"warnings must contain at most {MAX_AGENTS_PER_ROOM} entries"
  2309. )
  2310. if not all(isinstance(item, Mapping) for item in warnings):
  2311. raise ValueError("warnings must be a list of objects")
  2312. warnings_json = self._strict_json(
  2313. [dict(warning) for warning in warnings], "warnings"
  2314. )
  2315. if len(warnings_json.encode("utf-8")) > MAX_MESSAGE_BYTES:
  2316. raise ValueError("warnings exceed maximum size")
  2317. requested_warnings: list[str] = []
  2318. for warning in warnings:
  2319. message = warning.get("message")
  2320. requested_warnings.append(
  2321. self._message_text(
  2322. message,
  2323. "warning.message",
  2324. max_bytes=MAX_MESSAGE_BYTES,
  2325. nonblank=True,
  2326. )
  2327. )
  2328. return canonical_agent_ids, requested_warnings
  2329. def complete_cascade(self, source_run_id: str) -> dict[str, object]:
  2330. """Execute one frozen Mention plan exactly once and terminalize it."""
  2331. canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
  2332. request_id = self._cascade_request_id(canonical_source_id)
  2333. expected_hashes = {
  2334. self._cascade_request_hash(canonical_source_id, parse_version=1),
  2335. self._cascade_request_hash(canonical_source_id, parse_version=2),
  2336. }
  2337. with self.write_transaction() as connection:
  2338. ledger = connection.execute(
  2339. """SELECT request_id, operation, request_hash, response_json
  2340. FROM group_idempotency WHERE request_id = ?""",
  2341. (request_id,),
  2342. ).fetchone()
  2343. if ledger is None:
  2344. raise GroupNotFoundError("Cascade source not found")
  2345. if (
  2346. ledger["operation"] not in _CASCADE_OPERATIONS
  2347. or ledger["request_hash"] not in expected_hashes
  2348. ):
  2349. raise GroupStoreError("Stored cascade ledger is corrupt")
  2350. if ledger["operation"] != _CASCADE_PENDING_OPERATION:
  2351. return self._cascade_result(
  2352. ledger["response_json"], ledger["operation"]
  2353. )
  2354. plan = self._cascade_plan_from_ledger(ledger)
  2355. source = connection.execute(
  2356. "SELECT * FROM group_agent_runs WHERE id = ?",
  2357. (canonical_source_id,),
  2358. ).fetchone()
  2359. if source is None:
  2360. raise GroupStoreError("Stored cascade source is missing")
  2361. room = connection.execute(
  2362. "SELECT archived FROM group_rooms WHERE id = ?",
  2363. (source["room_id"],),
  2364. ).fetchone()
  2365. source_agent = connection.execute(
  2366. "SELECT enabled FROM group_agents WHERE id = ? AND room_id = ?",
  2367. (source["agent_id"], source["room_id"]),
  2368. ).fetchone()
  2369. if room is None:
  2370. raise GroupStoreError("Stored cascade ownership is corrupt")
  2371. if source["status"] != "completed":
  2372. raise GroupStoreError("Stored cascade source is not completed")
  2373. source_message = self._message_row(
  2374. connection, source["response_message_id"]
  2375. )
  2376. if (
  2377. source_message["id"] != plan["sourceMessageId"]
  2378. or source_message["status"] != "completed"
  2379. ):
  2380. raise GroupStoreError("Stored cascade message is corrupt")
  2381. if room["archived"] or source_agent is None or not source_agent["enabled"]:
  2382. result = self._cascade_summary([], [], state="discarded")
  2383. connection.execute(
  2384. """UPDATE group_idempotency
  2385. SET operation = ?, response_json = ? WHERE request_id = ?""",
  2386. (
  2387. _CASCADE_DISCARDED_OPERATION,
  2388. self._canonical_json(result),
  2389. request_id,
  2390. ),
  2391. )
  2392. return result
  2393. try:
  2394. canonical_ids, warning_texts = self._validated_cascade_inputs(
  2395. [target["agentId"] for target in plan["targets"]],
  2396. plan["warnings"],
  2397. )
  2398. reply_modes = {
  2399. target["agentId"]: target["replyMode"]
  2400. for target in plan["targets"]
  2401. }
  2402. except ValueError as error:
  2403. raise GroupStoreError("Stored cascade plan is corrupt") from error
  2404. created = self._enqueue_cascade_runs_transaction(
  2405. connection,
  2406. source=source,
  2407. canonical_agent_ids=canonical_ids,
  2408. requested_warnings=warning_texts,
  2409. reply_modes=reply_modes,
  2410. now=self._now(),
  2411. )
  2412. result = self._cascade_summary(
  2413. created["runs"], created["systemMessages"], state="completed"
  2414. )
  2415. connection.execute(
  2416. """UPDATE group_idempotency
  2417. SET operation = ?, response_json = ? WHERE request_id = ?""",
  2418. (
  2419. _CASCADE_COMPLETED_OPERATION,
  2420. self._canonical_json(result),
  2421. request_id,
  2422. ),
  2423. )
  2424. return result
  2425. @classmethod
  2426. def _cascade_result(cls, encoded: object, operation: str) -> dict[str, object]:
  2427. try:
  2428. result = cls._load_json(encoded)
  2429. except (TypeError, ValueError, json.JSONDecodeError) as error:
  2430. raise GroupStoreError("Stored cascade result is corrupt") from error
  2431. expected_state = (
  2432. "completed" if operation == _CASCADE_COMPLETED_OPERATION else "discarded"
  2433. )
  2434. expected_keys = {
  2435. "runCount",
  2436. "runIds",
  2437. "state",
  2438. "systemMessageCount",
  2439. "systemMessageIds",
  2440. }
  2441. if expected_state == "discarded":
  2442. expected_keys.add("discarded")
  2443. if (
  2444. not isinstance(result, dict)
  2445. or cls._canonical_json(result) != encoded
  2446. or set(result) != expected_keys
  2447. or result.get("state") != expected_state
  2448. or not isinstance(result.get("runIds"), list)
  2449. or not all(isinstance(item, str) for item in result["runIds"])
  2450. or len(result["runIds"]) > MAX_AGENTS_PER_ROOM
  2451. or len(result["runIds"]) != len(set(result["runIds"]))
  2452. or type(result.get("runCount")) is not int
  2453. or result.get("runCount") != len(result["runIds"])
  2454. or not isinstance(result.get("systemMessageIds"), list)
  2455. or not all(isinstance(item, str) for item in result["systemMessageIds"])
  2456. or len(result["systemMessageIds"]) > MAX_AGENTS_PER_ROOM
  2457. or len(result["systemMessageIds"]) != len(set(result["systemMessageIds"]))
  2458. or type(result.get("systemMessageCount")) is not int
  2459. or result.get("systemMessageCount") != len(result["systemMessageIds"])
  2460. or (expected_state == "discarded") != (result.get("discarded") is True)
  2461. ):
  2462. raise GroupStoreError("Stored cascade result is corrupt")
  2463. try:
  2464. if any(
  2465. cls._canonical_uuid(item, "runId") != item for item in result["runIds"]
  2466. ) or any(
  2467. cls._canonical_uuid(item, "messageId") != item
  2468. for item in result["systemMessageIds"]
  2469. ):
  2470. raise ValueError
  2471. except ValueError as error:
  2472. raise GroupStoreError("Stored cascade result is corrupt") from error
  2473. return result
  2474. @staticmethod
  2475. def _cascade_summary(
  2476. runs: list[Mapping[str, object]],
  2477. messages: list[Mapping[str, object]],
  2478. *,
  2479. state: str,
  2480. ) -> dict[str, object]:
  2481. result: dict[str, object] = {
  2482. "runCount": len(runs),
  2483. "runIds": [run["id"] for run in runs],
  2484. "state": state,
  2485. "systemMessageCount": len(messages),
  2486. "systemMessageIds": [message["id"] for message in messages],
  2487. }
  2488. if state == "discarded":
  2489. result["discarded"] = True
  2490. return result
  2491. def _enqueue_cascade_runs_transaction(
  2492. self,
  2493. connection: sqlite3.Connection,
  2494. *,
  2495. source: sqlite3.Row,
  2496. canonical_agent_ids: list[str],
  2497. requested_warnings: list[str],
  2498. now: float,
  2499. reply_modes: Mapping[str, str] | None = None,
  2500. ) -> dict[str, list[dict[str, object]]]:
  2501. room = self._active_room(connection, source["room_id"])
  2502. room_agents = connection.execute(
  2503. """SELECT * FROM group_agents WHERE room_id = ?
  2504. ORDER BY created_at ASC, id ASC""",
  2505. (source["room_id"],),
  2506. ).fetchall()
  2507. agents_by_id = {agent["id"]: agent for agent in room_agents}
  2508. warning_texts = list(requested_warnings)
  2509. next_depth = int(source["depth"]) + 1
  2510. max_reply_rounds = int(room["max_reply_rounds"])
  2511. if max_reply_rounds != -1 and next_depth >= max_reply_rounds:
  2512. warning_texts.append("Cascade depth limit reached")
  2513. canonical_agent_ids = []
  2514. source_message = self._message_row(connection, source["response_message_id"])
  2515. explicit_ids, _ = self._plan_cascade_mentions(
  2516. source_message["content"],
  2517. room_agents,
  2518. source_agent_id=source["agent_id"],
  2519. include_automatic=False,
  2520. )
  2521. explicit_set = set(explicit_ids)
  2522. created_runs: list[dict[str, object]] = []
  2523. for agent_id in canonical_agent_ids:
  2524. agent = agents_by_id.get(agent_id)
  2525. if agent is None:
  2526. warning_texts.append(f"Unknown Agent: {agent_id}")
  2527. continue
  2528. if not agent["enabled"]:
  2529. warning_texts.append(f"Agent disabled: {agent['display_name']}")
  2530. continue
  2531. duplicate = connection.execute(
  2532. """SELECT 1 FROM group_agent_runs
  2533. WHERE room_id = ? AND root_message_id = ?
  2534. AND agent_id = ? AND depth = ? LIMIT 1""",
  2535. (
  2536. source["room_id"],
  2537. source["root_message_id"],
  2538. agent_id,
  2539. next_depth,
  2540. ),
  2541. ).fetchone()
  2542. if duplicate is not None:
  2543. continue
  2544. reply_mode = (
  2545. reply_modes.get(agent_id, "mentioned")
  2546. if reply_modes is not None
  2547. else ("mentioned" if agent_id in explicit_set else "automatic")
  2548. )
  2549. if reply_mode not in {"mentioned", "automatic"}:
  2550. raise GroupStoreError("Stored cascade plan is corrupt")
  2551. visible = reply_mode == "mentioned"
  2552. response_id = str(uuid.uuid4())
  2553. run_id = str(uuid.uuid4())
  2554. connection.execute(
  2555. """INSERT INTO group_messages
  2556. (id, room_id, sender_kind, sender_id, sender_name,
  2557. root_message_id, reply_to_message_id, client_message_id,
  2558. content, reasoning, tool_state_json, status, error, visible,
  2559. created_at, updated_at)
  2560. VALUES (?, ?, 'agent', ?, ?, ?, ?, NULL,
  2561. '', '', '[]', 'queued', '', ?, ?, ?)""",
  2562. (
  2563. response_id,
  2564. source["room_id"],
  2565. agent_id,
  2566. agent["display_name"],
  2567. source["root_message_id"],
  2568. source["response_message_id"],
  2569. int(visible),
  2570. now,
  2571. now,
  2572. ),
  2573. )
  2574. connection.execute(
  2575. """INSERT INTO group_agent_runs
  2576. (id, room_id, agent_id, trigger_message_id,
  2577. response_message_id, root_message_id, depth, reply_mode, status,
  2578. runtime_session_id, error, created_at, updated_at)
  2579. VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, '', ?, ?)""",
  2580. (
  2581. run_id,
  2582. source["room_id"],
  2583. agent_id,
  2584. source["response_message_id"],
  2585. response_id,
  2586. source["root_message_id"],
  2587. next_depth,
  2588. reply_mode,
  2589. now,
  2590. now,
  2591. ),
  2592. )
  2593. message = self._message_wire(self._message_row(connection, response_id))
  2594. run = self._run_wire(self._run_row(connection, run_id))
  2595. if visible:
  2596. self._append_event(
  2597. connection,
  2598. source["room_id"],
  2599. "message.upsert",
  2600. message,
  2601. created_at=now,
  2602. )
  2603. self._append_event(
  2604. connection,
  2605. source["room_id"],
  2606. "run.updated",
  2607. run,
  2608. created_at=now,
  2609. )
  2610. created_runs.append(run)
  2611. system_messages: list[dict[str, object]] = []
  2612. for warning_text in list(dict.fromkeys(warning_texts))[:MAX_AGENTS_PER_ROOM]:
  2613. duplicate = connection.execute(
  2614. """SELECT * FROM group_messages
  2615. WHERE room_id = ? AND sender_kind = 'system'
  2616. AND root_message_id = ? AND reply_to_message_id = ?
  2617. AND content = ? AND status = 'completed'
  2618. ORDER BY seq ASC LIMIT 1""",
  2619. (
  2620. source["room_id"],
  2621. source["root_message_id"],
  2622. source["response_message_id"],
  2623. warning_text,
  2624. ),
  2625. ).fetchone()
  2626. if duplicate is not None:
  2627. continue
  2628. message_id = str(uuid.uuid4())
  2629. connection.execute(
  2630. """INSERT INTO group_messages
  2631. (id, room_id, sender_kind, sender_id, sender_name,
  2632. root_message_id, reply_to_message_id, client_message_id,
  2633. content, reasoning, tool_state_json, status, error,
  2634. created_at, updated_at)
  2635. VALUES (?, ?, 'system', 'system', '系统', ?, ?, NULL,
  2636. ?, '', '[]', 'completed', '', ?, ?)""",
  2637. (
  2638. message_id,
  2639. source["room_id"],
  2640. source["root_message_id"],
  2641. source["response_message_id"],
  2642. warning_text,
  2643. now,
  2644. now,
  2645. ),
  2646. )
  2647. message = self._message_wire(self._message_row(connection, message_id))
  2648. self._append_event(
  2649. connection,
  2650. source["room_id"],
  2651. "message.upsert",
  2652. message,
  2653. created_at=now,
  2654. )
  2655. system_messages.append(message)
  2656. return {"runs": created_runs, "systemMessages": system_messages}
  2657. def upsert_agent_message(
  2658. self,
  2659. run_id: str,
  2660. *,
  2661. content: str,
  2662. reasoning: str,
  2663. tool_state: object,
  2664. status: str,
  2665. error: str = "",
  2666. publish: bool = True,
  2667. ) -> dict[str, object]:
  2668. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2669. content = self._message_text(content, "content", max_bytes=MAX_MESSAGE_BYTES)
  2670. reasoning = self._message_text(
  2671. reasoning, "reasoning", max_bytes=MAX_MESSAGE_BYTES
  2672. )
  2673. error = self._message_text(error, "error", max_bytes=4096)
  2674. if not isinstance(status, str) or status not in _MESSAGE_STATUSES:
  2675. raise ValueError("status is invalid")
  2676. tool_json = self._tool_state_json(tool_state)
  2677. with self.write_transaction() as connection:
  2678. run = self._run_row(connection, canonical_run_id)
  2679. self._active_room(connection, run["room_id"])
  2680. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  2681. response = self._message_row(connection, run["response_message_id"])
  2682. if (
  2683. response["room_id"] != run["room_id"]
  2684. or response["sender_id"] != run["agent_id"]
  2685. ):
  2686. raise GroupStoreError("Run response message is corrupt")
  2687. self._validate_run_message_state(run, response)
  2688. if status not in _AGENT_MESSAGE_STATUSES_BY_RUN[run["status"]]:
  2689. raise GroupConflictError("Message status is invalid for run state")
  2690. if status not in _AGENT_MESSAGE_TRANSITIONS.get(
  2691. response["status"], frozenset()
  2692. ):
  2693. raise GroupConflictError("Message status cannot move backwards")
  2694. now = self._now()
  2695. visible = bool(response["visible"]) or publish
  2696. connection.execute(
  2697. """UPDATE group_messages SET content = ?, reasoning = ?, tool_state_json = ?,
  2698. status = ?, error = ?, visible = ?, updated_at = ? WHERE id = ?""",
  2699. (
  2700. content,
  2701. reasoning,
  2702. tool_json,
  2703. status,
  2704. error,
  2705. int(visible),
  2706. now,
  2707. run["response_message_id"],
  2708. ),
  2709. )
  2710. message = self._message_wire(
  2711. self._message_row(connection, run["response_message_id"])
  2712. )
  2713. if visible:
  2714. self._append_event(
  2715. connection,
  2716. run["room_id"],
  2717. "message.upsert",
  2718. message,
  2719. created_at=now,
  2720. )
  2721. return message
  2722. def transition_run(
  2723. self,
  2724. run_id: str,
  2725. status: str,
  2726. *,
  2727. runtime_session_id: object = UNSET,
  2728. error: object = UNSET,
  2729. ) -> dict[str, object]:
  2730. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2731. if not isinstance(status, str) or status not in RUN_TRANSITIONS:
  2732. raise ValueError("status is invalid")
  2733. runtime_value = (
  2734. self._runtime_session_id(runtime_session_id)
  2735. if runtime_session_id is not UNSET
  2736. else UNSET
  2737. )
  2738. error_value = (
  2739. self._message_text(error, "error", max_bytes=4096)
  2740. if error is not UNSET
  2741. else UNSET
  2742. )
  2743. with self.write_transaction() as connection:
  2744. run = self._run_row(connection, canonical_run_id)
  2745. self._active_room(connection, run["room_id"])
  2746. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  2747. response = self._message_row(connection, run["response_message_id"])
  2748. if (
  2749. response["room_id"] != run["room_id"]
  2750. or response["sender_id"] != run["agent_id"]
  2751. ):
  2752. raise GroupStoreError("Run response message is corrupt")
  2753. self._validate_run_message_state(run, response)
  2754. if status == run["status"]:
  2755. if status == "running":
  2756. if (
  2757. runtime_value is not UNSET
  2758. and runtime_value is not None
  2759. and run["runtime_session_id"] is not None
  2760. and runtime_value == run["runtime_session_id"]
  2761. ):
  2762. return self._run_wire(run)
  2763. raise GroupConflictError("Run is already claimed")
  2764. return self._run_wire(run)
  2765. if status not in RUN_TRANSITIONS[run["status"]]:
  2766. raise GroupConflictError("Illegal run status transition")
  2767. if status == "completed" and response["status"] != "completed":
  2768. raise GroupConflictError("Response message must be completed first")
  2769. if status not in {"failed", "interrupted"}:
  2770. self._validate_run_message_status(status, response["status"])
  2771. now = self._now()
  2772. if status in {"completed", "failed", "interrupted"}:
  2773. self._cancel_pending_interactions(connection, run, now)
  2774. result = self._update_run(
  2775. connection, run, status, now, runtime_value, error_value
  2776. )
  2777. if status in {"completed", "failed", "interrupted"}:
  2778. self._fail_claimed_interaction_ledgers(
  2779. connection,
  2780. run_id=run["id"],
  2781. reason=result["error"] or f"Run {status}",
  2782. runtime_session_ids=(
  2783. []
  2784. if run["runtime_session_id"] is None
  2785. else [run["runtime_session_id"]]
  2786. ),
  2787. run=result,
  2788. )
  2789. self._append_event(
  2790. connection, result["roomId"], "run.updated", result, created_at=now
  2791. )
  2792. if status in {"failed", "interrupted"}:
  2793. if response["status"] == "completed":
  2794. self._validate_run_message_status(status, response["status"])
  2795. else:
  2796. terminal_error = result["error"]
  2797. connection.execute(
  2798. """UPDATE group_messages
  2799. SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
  2800. (status, terminal_error, now, run["response_message_id"]),
  2801. )
  2802. message = self._message_wire(
  2803. self._message_row(connection, run["response_message_id"])
  2804. )
  2805. self._validate_run_message_status(
  2806. result["status"], message["status"]
  2807. )
  2808. if message["visible"]:
  2809. self._append_event(
  2810. connection,
  2811. result["roomId"],
  2812. "message.upsert",
  2813. message,
  2814. created_at=now,
  2815. )
  2816. return result
  2817. def bind_run_runtime(
  2818. self, run_id: str, runtime_session_id: str
  2819. ) -> dict[str, object]:
  2820. """Bind the first real runtime identity without reopening the run claim."""
  2821. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2822. runtime_value = self._runtime_session_id(runtime_session_id)
  2823. if runtime_value is None:
  2824. raise ValueError("runtimeSessionId is invalid")
  2825. with self.write_transaction() as connection:
  2826. run = self._run_row(connection, canonical_run_id)
  2827. self._active_room(connection, run["room_id"])
  2828. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  2829. response = self._message_row(connection, run["response_message_id"])
  2830. self._validate_run_message_state(run, response)
  2831. if run["status"] not in {"running", "awaiting_input"}:
  2832. raise GroupConflictError("Run does not accept a runtime binding")
  2833. if run["runtime_session_id"] == runtime_value:
  2834. return self._run_wire(run)
  2835. if run["runtime_session_id"] is not None:
  2836. raise GroupConflictError("Run runtime is already bound")
  2837. self._require_available_runtime(connection, runtime_value, canonical_run_id)
  2838. now = self._now()
  2839. result = self._update_run(
  2840. connection, run, run["status"], now, runtime_value, UNSET
  2841. )
  2842. self._append_event(
  2843. connection, run["room_id"], "run.updated", result, created_at=now
  2844. )
  2845. return result
  2846. def create_interaction(
  2847. self,
  2848. interaction_id: str,
  2849. run_id: str,
  2850. *,
  2851. kind: str,
  2852. payload: object,
  2853. ) -> dict[str, object]:
  2854. return self._create_gateway_interaction(
  2855. run_id,
  2856. kind=kind,
  2857. gateway_interaction_id=interaction_id,
  2858. payload=payload,
  2859. allow_awaiting=False,
  2860. )
  2861. def create_gateway_interaction(
  2862. self,
  2863. run_id: str,
  2864. *,
  2865. kind: str,
  2866. gateway_interaction_id: str | None,
  2867. payload: object,
  2868. ) -> dict[str, object]:
  2869. return self._create_gateway_interaction(
  2870. run_id,
  2871. kind=kind,
  2872. gateway_interaction_id=gateway_interaction_id,
  2873. payload=payload,
  2874. allow_awaiting=True,
  2875. )
  2876. def _create_gateway_interaction(
  2877. self,
  2878. run_id: str,
  2879. *,
  2880. kind: str,
  2881. gateway_interaction_id: str | None,
  2882. payload: object,
  2883. allow_awaiting: bool,
  2884. ) -> dict[str, object]:
  2885. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2886. if not isinstance(kind, str) or kind not in _INTERACTION_KINDS:
  2887. raise ValueError("kind is invalid")
  2888. payload_json = self._json_object(payload, "payload")
  2889. payload_value = self._load_json(payload_json)
  2890. clarification_gateway_id: str | None = None
  2891. if kind == "approval" and gateway_interaction_id is None:
  2892. interaction_id = f"approval-{uuid.uuid4()}"
  2893. elif gateway_interaction_id is None:
  2894. raise ValueError("Gateway clarification interactionId is required")
  2895. else:
  2896. gateway_id = self._interaction_id(gateway_interaction_id)
  2897. if kind == "clarification" and allow_awaiting:
  2898. if "gatewayRequestId" in payload_value:
  2899. raise ValueError("payload.gatewayRequestId is reserved")
  2900. payload_value["gatewayRequestId"] = gateway_id
  2901. payload_json = self._json_object(payload_value, "payload")
  2902. clarification_gateway_id = gateway_id
  2903. interaction_id = None
  2904. else:
  2905. interaction_id = gateway_id
  2906. try:
  2907. with self.write_transaction() as connection:
  2908. run = self._run_row(connection, canonical_run_id)
  2909. self._active_room(connection, run["room_id"])
  2910. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  2911. response = self._message_row(connection, run["response_message_id"])
  2912. self._validate_run_message_state(run, response)
  2913. accepted_statuses = (
  2914. {"running", "awaiting_input"} if allow_awaiting else {"running"}
  2915. )
  2916. if run["status"] not in accepted_statuses:
  2917. raise GroupConflictError("Interaction requires a running run")
  2918. self._validate_run_message_status("awaiting_input", response["status"])
  2919. if clarification_gateway_id is not None:
  2920. pending = connection.execute(
  2921. """SELECT * FROM group_interactions
  2922. WHERE run_id = ? AND kind = 'clarification'
  2923. AND status = 'pending' ORDER BY rowid ASC""",
  2924. (canonical_run_id,),
  2925. ).fetchall()
  2926. matching = []
  2927. for candidate in pending:
  2928. candidate_wire = self._interaction_wire(candidate)
  2929. if (
  2930. candidate_wire["payload"].get("gatewayRequestId")
  2931. == clarification_gateway_id
  2932. ):
  2933. matching.append(candidate)
  2934. if len(matching) > 1:
  2935. raise GroupStoreError(
  2936. "Stored clarification identities are not unique"
  2937. )
  2938. if matching:
  2939. existing = matching[0]
  2940. if existing["payload_json"] != payload_json:
  2941. raise GroupConflictError("Interaction already exists")
  2942. return self._interaction_wire(existing)
  2943. interaction_id = f"clarification-{uuid.uuid4()}"
  2944. if interaction_id is None:
  2945. raise GroupStoreError("Interaction identity is missing")
  2946. existing = connection.execute(
  2947. "SELECT * FROM group_interactions WHERE id = ?",
  2948. (interaction_id,),
  2949. ).fetchone()
  2950. if existing is not None:
  2951. if (
  2952. existing["room_id"] != run["room_id"]
  2953. or existing["agent_id"] != run["agent_id"]
  2954. or existing["run_id"] != canonical_run_id
  2955. or existing["kind"] != kind
  2956. or existing["payload_json"] != payload_json
  2957. ):
  2958. raise GroupConflictError("Interaction already exists")
  2959. return self._interaction_wire(existing)
  2960. now = self._now()
  2961. connection.execute(
  2962. """INSERT INTO group_interactions
  2963. (id, room_id, agent_id, run_id, kind, payload_json, status, created_at, resolved_at)
  2964. VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)""",
  2965. (
  2966. interaction_id,
  2967. run["room_id"],
  2968. run["agent_id"],
  2969. canonical_run_id,
  2970. kind,
  2971. payload_json,
  2972. now,
  2973. ),
  2974. )
  2975. interaction = self._interaction_wire(
  2976. self._interaction_row(connection, interaction_id)
  2977. )
  2978. self._append_event(
  2979. connection,
  2980. run["room_id"],
  2981. "interaction.requested",
  2982. interaction,
  2983. created_at=now,
  2984. )
  2985. if run["status"] == "running":
  2986. changed = self._update_run(
  2987. connection, run, "awaiting_input", now, UNSET, UNSET
  2988. )
  2989. self._append_event(
  2990. connection,
  2991. run["room_id"],
  2992. "run.updated",
  2993. changed,
  2994. created_at=now,
  2995. )
  2996. return interaction
  2997. except sqlite3.IntegrityError as error:
  2998. if "group_interactions.id" in str(error):
  2999. raise GroupConflictError("Interaction already exists") from error
  3000. raise self._integrity_conflict(error) from error
  3001. def resolve_interaction(
  3002. self, interaction_id: str, *, status: str = "resolved"
  3003. ) -> dict[str, object]:
  3004. interaction_id = self._interaction_id(interaction_id)
  3005. if not isinstance(status, str) or status not in _INTERACTION_TERMINAL_STATUSES:
  3006. raise ValueError("status must be resolved or cancelled")
  3007. with self.write_transaction() as connection:
  3008. interaction = self._interaction_row(connection, interaction_id)
  3009. if interaction["status"] != "pending":
  3010. raise GroupConflictError("Interaction is already resolved")
  3011. run = self._run_row(connection, interaction["run_id"])
  3012. self._active_room(connection, run["room_id"])
  3013. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3014. response = self._message_row(connection, run["response_message_id"])
  3015. self._validate_run_message_state(run, response)
  3016. now = self._now()
  3017. connection.execute(
  3018. "UPDATE group_interactions SET status = ?, resolved_at = ? WHERE id = ?",
  3019. (status, now, interaction_id),
  3020. )
  3021. result = self._interaction_wire(
  3022. self._interaction_row(connection, interaction_id)
  3023. )
  3024. self._append_event(
  3025. connection,
  3026. result["roomId"],
  3027. "interaction.resolved",
  3028. result,
  3029. created_at=now,
  3030. )
  3031. if status == "resolved":
  3032. if run["status"] != "awaiting_input":
  3033. raise GroupConflictError("Interaction run is not awaiting input")
  3034. remaining = connection.execute(
  3035. """SELECT 1 FROM group_interactions
  3036. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  3037. (run["id"],),
  3038. ).fetchone()
  3039. if remaining is None:
  3040. self._validate_run_message_status("running", response["status"])
  3041. changed = self._update_run(
  3042. connection, run, "running", now, UNSET, UNSET
  3043. )
  3044. self._append_event(
  3045. connection,
  3046. changed["roomId"],
  3047. "run.updated",
  3048. changed,
  3049. created_at=now,
  3050. )
  3051. run_result = changed
  3052. else:
  3053. run_result = self._run_wire(run)
  3054. else:
  3055. run_result = self._run_wire(run)
  3056. self._fail_claimed_interaction_ledgers(
  3057. connection,
  3058. run_id=run["id"],
  3059. interaction_id=interaction_id,
  3060. reason=f"Interaction {status}",
  3061. runtime_session_ids=(
  3062. []
  3063. if run["runtime_session_id"] is None
  3064. else [run["runtime_session_id"]]
  3065. ),
  3066. run=run_result,
  3067. )
  3068. return result
  3069. def begin_interaction_response(
  3070. self,
  3071. room_id: str,
  3072. interaction_id: str,
  3073. *,
  3074. request_id: str,
  3075. kind: str,
  3076. response: Mapping[str, object],
  3077. ) -> dict[str, object]:
  3078. """Durably claim one FIFO Gateway response without a public status."""
  3079. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  3080. interaction_id = self._interaction_id(interaction_id)
  3081. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  3082. if kind not in _INTERACTION_KINDS:
  3083. raise ValueError("kind is invalid")
  3084. response_json = self._json_object(response, "response")
  3085. response_value = self._load_json(response_json)
  3086. legacy_operation = f"interaction.{kind}.response"
  3087. operation = self._interaction_operation(kind, interaction_id)
  3088. payload = {
  3089. "roomId": canonical_room_id,
  3090. "interactionId": interaction_id,
  3091. "kind": kind,
  3092. "response": response_value,
  3093. }
  3094. request_hash = hashlib.sha256(
  3095. self._canonical_json(payload).encode()
  3096. ).hexdigest()
  3097. with self.write_transaction() as connection:
  3098. existing = connection.execute(
  3099. """SELECT operation, request_hash, response_json
  3100. FROM group_idempotency WHERE request_id = ?""",
  3101. (canonical_request_id,),
  3102. ).fetchone()
  3103. if existing is not None:
  3104. if (
  3105. existing["operation"] not in {operation, legacy_operation}
  3106. or existing["request_hash"] != request_hash
  3107. ):
  3108. raise IdempotencyConflict(
  3109. "requestId was already used for a different request"
  3110. )
  3111. state = self._idempotency_state(existing["response_json"])
  3112. if state["state"] == "claimed":
  3113. raise GroupConflictError(
  3114. "Interaction response is already in progress"
  3115. )
  3116. if state["state"] == "completed":
  3117. return {"state": "replay", "response": state["response"]}
  3118. if state["state"] == "failed":
  3119. return state
  3120. raise GroupStoreError("Stored interaction response is corrupt")
  3121. competing = connection.execute(
  3122. """SELECT operation, response_json FROM group_idempotency
  3123. WHERE operation IN (?, ?)""",
  3124. (operation, legacy_operation),
  3125. ).fetchall()
  3126. for candidate in competing:
  3127. state = self._idempotency_state(candidate["response_json"])
  3128. if (
  3129. state["state"] == "claimed"
  3130. and state["interactionId"] == interaction_id
  3131. ):
  3132. raise GroupConflictError("Interaction response is already claimed")
  3133. interaction = self._interaction_row(connection, interaction_id)
  3134. if interaction["room_id"] != canonical_room_id:
  3135. raise GroupNotFoundError("Interaction not found")
  3136. if interaction["kind"] != kind:
  3137. raise GroupConflictError("Interaction kind does not match")
  3138. if interaction["status"] != "pending":
  3139. raise GroupConflictError("Interaction is already resolved")
  3140. run = self._run_row(connection, interaction["run_id"])
  3141. self._active_room(connection, canonical_room_id)
  3142. self._enabled_agent(connection, canonical_room_id, run["agent_id"])
  3143. if run["status"] != "awaiting_input":
  3144. raise GroupConflictError("Interaction run is not awaiting input")
  3145. if run["runtime_session_id"] is None:
  3146. raise GroupConflictError("Interaction run has no runtime session")
  3147. first = connection.execute(
  3148. """SELECT id FROM group_interactions
  3149. WHERE run_id = ? AND kind = ? AND status = 'pending'
  3150. ORDER BY rowid ASC LIMIT 1""",
  3151. (run["id"], kind),
  3152. ).fetchone()
  3153. if first is None or first["id"] != interaction_id:
  3154. raise GroupConflictError(
  3155. "Interaction responses must preserve FIFO order"
  3156. )
  3157. sentinel = {
  3158. "state": "claimed",
  3159. "interactionId": interaction_id,
  3160. "kind": kind,
  3161. }
  3162. connection.execute(
  3163. """INSERT INTO group_idempotency
  3164. (request_id, operation, request_hash, response_json, created_at)
  3165. VALUES (?, ?, ?, ?, ?)""",
  3166. (
  3167. canonical_request_id,
  3168. operation,
  3169. request_hash,
  3170. self._canonical_json(sentinel),
  3171. self._now(),
  3172. ),
  3173. )
  3174. return {
  3175. "state": "claimed",
  3176. "interaction": self._interaction_wire(interaction),
  3177. "run": self._run_wire(run),
  3178. }
  3179. def finish_interaction_response(
  3180. self,
  3181. request_id: str,
  3182. *,
  3183. response: Mapping[str, object],
  3184. interaction_status: str = "resolved",
  3185. ) -> dict[str, object]:
  3186. """Commit a known Gateway response and release the run when possible."""
  3187. if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
  3188. raise ValueError("interaction_status must be resolved or cancelled")
  3189. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  3190. response_json = self._json_object(response, "response")
  3191. public_response = self._load_json(response_json)
  3192. with self.write_transaction() as connection:
  3193. claim = connection.execute(
  3194. """SELECT operation, response_json FROM group_idempotency
  3195. WHERE request_id = ?""",
  3196. (canonical_request_id,),
  3197. ).fetchone()
  3198. operation = (
  3199. None
  3200. if claim is None
  3201. else self._interaction_response_operation(claim["operation"])
  3202. )
  3203. if claim is None or operation is None:
  3204. raise GroupNotFoundError("Interaction response claim not found")
  3205. state = self._idempotency_state(claim["response_json"])
  3206. if state["state"] == "claimed" and (
  3207. operation[0] != state["kind"]
  3208. or (operation[1] is not None and operation[1] != state["interactionId"])
  3209. ):
  3210. raise GroupStoreError("Stored interaction response is corrupt")
  3211. if state["state"] == "completed":
  3212. stored_status = state.get("interactionStatus", "resolved")
  3213. if stored_status != interaction_status:
  3214. raise GroupConflictError(
  3215. "Interaction response terminal status changed"
  3216. )
  3217. return state["response"]
  3218. if state["state"] != "claimed":
  3219. raise GroupConflictError("Interaction response claim is terminal")
  3220. interaction = self._interaction_row(connection, state["interactionId"])
  3221. if interaction["status"] != "pending":
  3222. raise GroupConflictError("Interaction is already resolved")
  3223. run = self._run_row(connection, interaction["run_id"])
  3224. self._active_room(connection, run["room_id"])
  3225. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3226. if run["status"] != "awaiting_input":
  3227. raise GroupConflictError("Interaction run is not awaiting input")
  3228. now = self._now()
  3229. connection.execute(
  3230. """UPDATE group_interactions
  3231. SET status = ?, resolved_at = ? WHERE id = ?""",
  3232. (interaction_status, now, interaction["id"]),
  3233. )
  3234. resolved = self._interaction_wire(
  3235. self._interaction_row(connection, interaction["id"])
  3236. )
  3237. self._append_event(
  3238. connection,
  3239. run["room_id"],
  3240. "interaction.resolved",
  3241. resolved,
  3242. created_at=now,
  3243. )
  3244. pending = connection.execute(
  3245. """SELECT 1 FROM group_interactions
  3246. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  3247. (run["id"],),
  3248. ).fetchone()
  3249. if pending is None:
  3250. response_row = self._message_row(connection, run["response_message_id"])
  3251. self._validate_run_message_status("running", response_row["status"])
  3252. changed = self._update_run(
  3253. connection, run, "running", now, UNSET, UNSET
  3254. )
  3255. self._append_event(
  3256. connection,
  3257. run["room_id"],
  3258. "run.updated",
  3259. changed,
  3260. created_at=now,
  3261. )
  3262. final = {
  3263. "state": "completed",
  3264. "interactionStatus": interaction_status,
  3265. "response": public_response,
  3266. }
  3267. connection.execute(
  3268. """UPDATE group_idempotency SET response_json = ?
  3269. WHERE request_id = ?""",
  3270. (self._canonical_json(final), canonical_request_id),
  3271. )
  3272. return public_response
  3273. def fail_interaction_response(
  3274. self, request_id: str, *, reason: str, uncertain: bool
  3275. ) -> dict[str, object]:
  3276. """Fail closed on an unknown Gateway outcome or release a retryable claim."""
  3277. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  3278. failure_reason = self._message_text(
  3279. reason, "reason", max_bytes=4096, nonblank=True
  3280. )
  3281. if not isinstance(uncertain, bool):
  3282. raise ValueError("uncertain must be a boolean")
  3283. with self.write_transaction() as connection:
  3284. claim = connection.execute(
  3285. """SELECT operation, response_json FROM group_idempotency
  3286. WHERE request_id = ?""",
  3287. (canonical_request_id,),
  3288. ).fetchone()
  3289. operation = (
  3290. None
  3291. if claim is None
  3292. else self._interaction_response_operation(claim["operation"])
  3293. )
  3294. if claim is None or operation is None:
  3295. raise GroupNotFoundError("Interaction response claim not found")
  3296. state = self._idempotency_state(claim["response_json"])
  3297. if state["state"] == "claimed" and (
  3298. operation[0] != state["kind"]
  3299. or (operation[1] is not None and operation[1] != state["interactionId"])
  3300. ):
  3301. raise GroupStoreError("Stored interaction response is corrupt")
  3302. if state["state"] == "failed":
  3303. return state
  3304. if state["state"] != "claimed":
  3305. raise GroupConflictError("Interaction response claim is terminal")
  3306. interaction = self._interaction_row(connection, state["interactionId"])
  3307. run = self._run_row(connection, interaction["run_id"])
  3308. self._active_room(connection, run["room_id"])
  3309. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3310. if run["status"] != "awaiting_input":
  3311. raise GroupConflictError("Interaction run is not awaiting input")
  3312. if not uncertain:
  3313. connection.execute(
  3314. "DELETE FROM group_idempotency WHERE request_id = ?",
  3315. (canonical_request_id,),
  3316. )
  3317. return {"state": "retryable"}
  3318. runtime_ids = (
  3319. [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
  3320. )
  3321. now = self._now()
  3322. self._cancel_pending_interactions(connection, run, now)
  3323. response_row = self._message_row(connection, run["response_message_id"])
  3324. changed = self._update_run(
  3325. connection, run, "failed", now, None, failure_reason
  3326. )
  3327. self._append_event(
  3328. connection,
  3329. run["room_id"],
  3330. "run.updated",
  3331. changed,
  3332. created_at=now,
  3333. )
  3334. if response_row["status"] != "completed":
  3335. connection.execute(
  3336. """UPDATE group_messages
  3337. SET status = 'failed', error = ?, updated_at = ? WHERE id = ?""",
  3338. (failure_reason, now, response_row["id"]),
  3339. )
  3340. message = self._message_wire(
  3341. self._message_row(connection, response_row["id"])
  3342. )
  3343. if message["visible"]:
  3344. self._append_event(
  3345. connection,
  3346. run["room_id"],
  3347. "message.upsert",
  3348. message,
  3349. created_at=now,
  3350. )
  3351. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  3352. final = {
  3353. "state": "failed",
  3354. "reason": failure_reason,
  3355. "runtimeSessionIds": runtime_ids,
  3356. "run": changed,
  3357. }
  3358. self._fail_claimed_interaction_ledgers(
  3359. connection,
  3360. run_id=run["id"],
  3361. reason=failure_reason,
  3362. runtime_session_ids=runtime_ids,
  3363. run=changed,
  3364. )
  3365. connection.execute(
  3366. """UPDATE group_idempotency SET response_json = ?
  3367. WHERE request_id = ?""",
  3368. (self._canonical_json(final), canonical_request_id),
  3369. )
  3370. return final
  3371. def expire_interaction(self, interaction_id: str) -> dict[str, object]:
  3372. """Idempotently cancel a stale interaction and resume when it was last."""
  3373. interaction_id = self._interaction_id(interaction_id)
  3374. with self.write_transaction() as connection:
  3375. interaction = self._interaction_row(connection, interaction_id)
  3376. if interaction["status"] != "pending":
  3377. return self._interaction_wire(interaction)
  3378. run = self._run_row(connection, interaction["run_id"])
  3379. self._active_room(connection, run["room_id"])
  3380. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3381. now = self._now()
  3382. connection.execute(
  3383. """UPDATE group_interactions
  3384. SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
  3385. (now, interaction_id),
  3386. )
  3387. result = self._interaction_wire(
  3388. self._interaction_row(connection, interaction_id)
  3389. )
  3390. self._append_event(
  3391. connection,
  3392. run["room_id"],
  3393. "interaction.resolved",
  3394. result,
  3395. created_at=now,
  3396. )
  3397. remaining = connection.execute(
  3398. """SELECT 1 FROM group_interactions
  3399. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  3400. (run["id"],),
  3401. ).fetchone()
  3402. if run["status"] == "awaiting_input" and remaining is None:
  3403. response = self._message_row(connection, run["response_message_id"])
  3404. self._validate_run_message_status("running", response["status"])
  3405. changed = self._update_run(
  3406. connection, run, "running", now, UNSET, UNSET
  3407. )
  3408. self._append_event(
  3409. connection,
  3410. run["room_id"],
  3411. "run.updated",
  3412. changed,
  3413. created_at=now,
  3414. )
  3415. run_result = changed
  3416. else:
  3417. run_result = self._run_wire(run)
  3418. self._fail_claimed_interaction_ledgers(
  3419. connection,
  3420. run_id=run["id"],
  3421. interaction_id=interaction_id,
  3422. reason="Interaction expired",
  3423. runtime_session_ids=(
  3424. []
  3425. if run["runtime_session_id"] is None
  3426. else [run["runtime_session_id"]]
  3427. ),
  3428. run=run_result,
  3429. )
  3430. return result
  3431. def events_after(
  3432. self, cursor: int, limit: int = MAX_EVENT_BATCH_SIZE
  3433. ) -> list[dict[str, object]]:
  3434. cursor = self._nonnegative_int(cursor, "cursor")
  3435. self._page_limit(limit, MAX_EVENT_BATCH_SIZE, "limit")
  3436. with self.read_transaction() as connection:
  3437. current_epoch = self._validated_epoch(
  3438. self._metadata_value_from_connection(connection, "journal_epoch")
  3439. )
  3440. rows = connection.execute(
  3441. "SELECT * FROM group_events WHERE cursor > ? ORDER BY cursor ASC LIMIT ?",
  3442. (cursor, limit),
  3443. ).fetchall()
  3444. return [self._event_wire(row, current_epoch) for row in rows]
  3445. def cursor_status(self, epoch: str, cursor: int) -> str:
  3446. canonical_epoch = self._canonical_uuid(epoch, "epoch")
  3447. cursor = self._nonnegative_int(cursor, "cursor")
  3448. with self.read_transaction() as connection:
  3449. if canonical_epoch != self._validated_epoch(
  3450. self._metadata_value_from_connection(connection, "journal_epoch")
  3451. ):
  3452. return "epoch_mismatch"
  3453. bounds = connection.execute(
  3454. "SELECT MIN(cursor) AS oldest, MAX(cursor) AS latest FROM group_events"
  3455. ).fetchone()
  3456. latest = int(bounds["latest"] or 0)
  3457. if cursor > latest:
  3458. return "cursor_expired"
  3459. oldest = bounds["oldest"]
  3460. if oldest is not None and cursor < int(oldest) - 1:
  3461. return "cursor_expired"
  3462. return "ok"
  3463. def prune_events(self, now: float | None = None) -> int:
  3464. prune_now = self._now() if now is None else self._finite_timestamp(now, "now")
  3465. with self.write_transaction() as connection:
  3466. threshold = connection.execute(
  3467. "SELECT cursor FROM group_events ORDER BY cursor DESC LIMIT 1 OFFSET ?",
  3468. (MIN_RETAINED_EVENTS - 1,),
  3469. ).fetchone()
  3470. if threshold is None:
  3471. return 0
  3472. result = connection.execute(
  3473. "DELETE FROM group_events WHERE created_at < ? AND cursor < ?",
  3474. (prune_now - EVENT_RETENTION_SECONDS, threshold["cursor"]),
  3475. )
  3476. return result.rowcount
  3477. def _interrupt_runs_for_scope(
  3478. self,
  3479. connection: sqlite3.Connection,
  3480. *,
  3481. room_id: str,
  3482. reason: str,
  3483. now: float,
  3484. agent_id: str | None = None,
  3485. include_queued: bool = True,
  3486. ) -> dict[str, list[str]]:
  3487. statuses = (
  3488. "('queued', 'running', 'awaiting_input')"
  3489. if include_queued
  3490. else "('running', 'awaiting_input')"
  3491. )
  3492. query = f"""SELECT run.* FROM group_agent_runs AS run
  3493. JOIN group_messages AS response
  3494. ON response.id = run.response_message_id
  3495. WHERE run.room_id = ? AND run.status IN {statuses}"""
  3496. params: list[object] = [room_id]
  3497. if agent_id is not None:
  3498. query += " AND run.agent_id = ?"
  3499. params.append(agent_id)
  3500. query += " ORDER BY response.seq ASC, run.id ASC"
  3501. runs = connection.execute(query, params).fetchall()
  3502. changed_ids: list[str] = []
  3503. runtime_ids: list[str] = []
  3504. for run in runs:
  3505. run_runtime_ids = (
  3506. [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
  3507. )
  3508. if (
  3509. run["runtime_session_id"] is not None
  3510. and run["runtime_session_id"] not in runtime_ids
  3511. ):
  3512. runtime_ids.append(run["runtime_session_id"])
  3513. response = self._message_row(connection, run["response_message_id"])
  3514. if (
  3515. response["room_id"] != run["room_id"]
  3516. or response["sender_id"] != run["agent_id"]
  3517. ):
  3518. raise GroupStoreError("Run response message is corrupt")
  3519. self._validate_run_message_state(run, response)
  3520. changed = self._update_run(
  3521. connection, run, "interrupted", now, None, reason
  3522. )
  3523. self._append_event(
  3524. connection, room_id, "run.updated", changed, created_at=now
  3525. )
  3526. if response["status"] == "completed":
  3527. self._validate_run_message_status(changed["status"], response["status"])
  3528. else:
  3529. connection.execute(
  3530. """UPDATE group_messages
  3531. SET status = 'interrupted', error = ?, updated_at = ? WHERE id = ?""",
  3532. (reason, now, run["response_message_id"]),
  3533. )
  3534. message = self._message_wire(
  3535. self._message_row(connection, run["response_message_id"])
  3536. )
  3537. self._validate_run_message_status(changed["status"], message["status"])
  3538. if message["visible"]:
  3539. self._append_event(
  3540. connection,
  3541. room_id,
  3542. "message.upsert",
  3543. message,
  3544. created_at=now,
  3545. )
  3546. self._cancel_pending_interactions(
  3547. connection, run, now, order_by_created_at=True
  3548. )
  3549. self._fail_claimed_interaction_ledgers(
  3550. connection,
  3551. run_id=run["id"],
  3552. reason=reason,
  3553. runtime_session_ids=run_runtime_ids,
  3554. run=changed,
  3555. )
  3556. changed_ids.append(run["id"])
  3557. return {"runIds": changed_ids, "runtimeSessionIds": runtime_ids}
  3558. def recover_after_restart(self) -> list[str]:
  3559. with self.write_transaction() as connection:
  3560. runs = connection.execute(
  3561. "SELECT * FROM group_agent_runs WHERE status IN ('running', 'awaiting_input') ORDER BY created_at ASC, id ASC"
  3562. ).fetchall()
  3563. if not runs:
  3564. return []
  3565. now = self._now()
  3566. changed_ids: list[str] = []
  3567. for run in runs:
  3568. runtime_ids = (
  3569. []
  3570. if run["runtime_session_id"] is None
  3571. else [run["runtime_session_id"]]
  3572. )
  3573. response = self._message_row(connection, run["response_message_id"])
  3574. if (
  3575. response["room_id"] != run["room_id"]
  3576. or response["sender_id"] != run["agent_id"]
  3577. ):
  3578. raise GroupStoreError("Run response message is corrupt")
  3579. self._validate_run_message_state(run, response)
  3580. changed = self._update_run(
  3581. connection, run, "interrupted", now, None, "Dashboard restarted"
  3582. )
  3583. self._append_event(
  3584. connection, run["room_id"], "run.updated", changed, created_at=now
  3585. )
  3586. if response["status"] == "completed":
  3587. self._validate_run_message_status(
  3588. changed["status"], response["status"]
  3589. )
  3590. else:
  3591. connection.execute(
  3592. """UPDATE group_messages
  3593. SET status = 'interrupted', error = 'Dashboard restarted',
  3594. updated_at = ? WHERE id = ?""",
  3595. (now, run["response_message_id"]),
  3596. )
  3597. message = self._message_wire(
  3598. self._message_row(connection, run["response_message_id"])
  3599. )
  3600. self._validate_run_message_status(
  3601. changed["status"], message["status"]
  3602. )
  3603. if message["visible"]:
  3604. self._append_event(
  3605. connection,
  3606. run["room_id"],
  3607. "message.upsert",
  3608. message,
  3609. created_at=now,
  3610. )
  3611. self._cancel_pending_interactions(
  3612. connection, run, now, order_by_created_at=True
  3613. )
  3614. self._fail_claimed_interaction_ledgers(
  3615. connection,
  3616. run_id=run["id"],
  3617. reason="Dashboard restarted",
  3618. runtime_session_ids=runtime_ids,
  3619. run=changed,
  3620. )
  3621. changed_ids.append(run["id"])
  3622. return changed_ids
  3623. def _cancel_pending_interactions(
  3624. self,
  3625. connection: sqlite3.Connection,
  3626. run: sqlite3.Row,
  3627. now: float,
  3628. *,
  3629. order_by_created_at: bool = False,
  3630. ) -> list[dict[str, object]]:
  3631. """Cancel a run's pending cards and publish their durable resolutions."""
  3632. ordering = "created_at ASC, id ASC" if order_by_created_at else "rowid ASC"
  3633. interactions = connection.execute(
  3634. f"""SELECT id FROM group_interactions
  3635. WHERE run_id = ? AND status = 'pending' ORDER BY {ordering}""",
  3636. (run["id"],),
  3637. ).fetchall()
  3638. cancelled: list[dict[str, object]] = []
  3639. for interaction in interactions:
  3640. connection.execute(
  3641. """UPDATE group_interactions
  3642. SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
  3643. (now, interaction["id"]),
  3644. )
  3645. resolved = self._interaction_wire(
  3646. self._interaction_row(connection, interaction["id"])
  3647. )
  3648. self._append_event(
  3649. connection,
  3650. run["room_id"],
  3651. "interaction.resolved",
  3652. resolved,
  3653. created_at=now,
  3654. )
  3655. cancelled.append(resolved)
  3656. return cancelled
  3657. def _fail_claimed_interaction_ledgers(
  3658. self,
  3659. connection: sqlite3.Connection,
  3660. *,
  3661. run_id: str,
  3662. reason: str,
  3663. runtime_session_ids: list[str],
  3664. run: Mapping[str, object],
  3665. interaction_id: str | None = None,
  3666. ) -> None:
  3667. interactions = connection.execute(
  3668. """SELECT id, kind FROM group_interactions
  3669. WHERE run_id = ? ORDER BY rowid ASC""",
  3670. (run_id,),
  3671. ).fetchall()
  3672. if interaction_id is not None:
  3673. interactions = [
  3674. item for item in interactions if item["id"] == interaction_id
  3675. ]
  3676. if not interactions:
  3677. return
  3678. target_ids = {item["id"] for item in interactions}
  3679. scoped_operations = [
  3680. self._interaction_operation(item["kind"], item["id"])
  3681. for item in interactions
  3682. ]
  3683. placeholders = ", ".join("?" for _ in scoped_operations)
  3684. ledgers = connection.execute(
  3685. f"""SELECT request_id, operation, response_json
  3686. FROM group_idempotency WHERE operation IN ({placeholders})""",
  3687. scoped_operations,
  3688. ).fetchall()
  3689. legacy = connection.execute(
  3690. """SELECT request_id, operation, response_json
  3691. FROM group_idempotency WHERE operation IN (
  3692. 'interaction.approval.response',
  3693. 'interaction.clarification.response'
  3694. )"""
  3695. ).fetchall()
  3696. seen: set[str] = set()
  3697. terminal = {
  3698. "state": "failed",
  3699. "reason": reason,
  3700. "runtimeSessionIds": list(runtime_session_ids),
  3701. "run": dict(run),
  3702. }
  3703. encoded = self._canonical_json(terminal)
  3704. for ledger in (*ledgers, *legacy):
  3705. if ledger["request_id"] in seen:
  3706. continue
  3707. seen.add(ledger["request_id"])
  3708. operation = self._interaction_response_operation(ledger["operation"])
  3709. state = self._idempotency_state(ledger["response_json"])
  3710. if operation is None or state["state"] != "claimed":
  3711. continue
  3712. claimed_id = state["interactionId"]
  3713. if claimed_id not in target_ids:
  3714. continue
  3715. if operation[0] != state["kind"] or (
  3716. operation[1] is not None and operation[1] != claimed_id
  3717. ):
  3718. raise GroupStoreError("Stored interaction response is corrupt")
  3719. connection.execute(
  3720. """UPDATE group_idempotency SET response_json = ?
  3721. WHERE request_id = ?""",
  3722. (encoded, ledger["request_id"]),
  3723. )
  3724. def queued_run_count(self) -> int:
  3725. with self.connection() as connection:
  3726. return int(
  3727. connection.execute(
  3728. "SELECT COUNT(*) FROM group_agent_runs WHERE status = 'queued'"
  3729. ).fetchone()[0]
  3730. )
  3731. def list_pending_interactions(self, room_id: str) -> list[dict[str, object]]:
  3732. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  3733. with self.read_transaction() as connection:
  3734. self._room_detail(connection, canonical_room_id, include_archived=True)
  3735. rows = connection.execute(
  3736. "SELECT * FROM group_interactions WHERE room_id = ? AND status = 'pending' ORDER BY created_at, id",
  3737. (canonical_room_id,),
  3738. ).fetchall()
  3739. return [self._interaction_wire(row) for row in rows]
  3740. def list_queued_runs(self, room_id: str) -> list[dict[str, object]]:
  3741. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  3742. with self.read_transaction() as connection:
  3743. self._room_detail(connection, canonical_room_id, include_archived=True)
  3744. rows = connection.execute(
  3745. "SELECT * FROM group_agent_runs WHERE room_id = ? AND status = 'queued' ORDER BY created_at, id",
  3746. (canonical_room_id,),
  3747. ).fetchall()
  3748. return [self._run_wire(row) for row in rows]
  3749. def latest_cursor(self) -> int:
  3750. with self.connection() as connection:
  3751. row = connection.execute(
  3752. "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
  3753. ).fetchone()
  3754. return int(row["cursor"])
  3755. @staticmethod
  3756. def _safe_context_seq(
  3757. connection: sqlite3.Connection,
  3758. room_id: str,
  3759. after_seq: int,
  3760. trigger_seq: int,
  3761. ) -> int:
  3762. hole = connection.execute(
  3763. """SELECT MIN(seq) AS seq FROM group_messages
  3764. WHERE room_id = ? AND seq > ? AND seq <= ?
  3765. AND status NOT IN ('completed', 'failed', 'interrupted')""",
  3766. (room_id, after_seq, trigger_seq),
  3767. ).fetchone()["seq"]
  3768. if hole is None:
  3769. return max(after_seq, trigger_seq)
  3770. return max(after_seq, int(hole) - 1)
  3771. def _append_agent_status(
  3772. self,
  3773. connection: sqlite3.Connection,
  3774. room_id: str,
  3775. agent_id: str,
  3776. now: float,
  3777. ) -> None:
  3778. row = connection.execute(
  3779. """SELECT id, status FROM group_agent_runs
  3780. WHERE room_id = ? AND agent_id = ?
  3781. AND status IN ('queued', 'running', 'awaiting_input')
  3782. ORDER BY CASE status
  3783. WHEN 'awaiting_input' THEN 3
  3784. WHEN 'running' THEN 2
  3785. ELSE 1 END DESC,
  3786. created_at ASC, id ASC
  3787. LIMIT 1""",
  3788. (room_id, agent_id),
  3789. ).fetchone()
  3790. payload: dict[str, object] = {
  3791. "roomId": room_id,
  3792. "agentId": agent_id,
  3793. "status": "idle" if row is None else row["status"],
  3794. "runId": None if row is None else row["id"],
  3795. }
  3796. self._append_event(connection, room_id, "agent.status", payload, created_at=now)
  3797. def _append_event(
  3798. self,
  3799. connection: sqlite3.Connection,
  3800. room_id: str,
  3801. event_type: str,
  3802. payload: Mapping[str, object],
  3803. *,
  3804. created_at: float | None = None,
  3805. ) -> int:
  3806. epoch = self._metadata_value_from_connection(connection, "journal_epoch")
  3807. cursor = connection.execute(
  3808. """INSERT INTO group_events(epoch, room_id, event_type, payload_json, created_at)
  3809. VALUES (?, ?, ?, ?, ?) RETURNING cursor""",
  3810. (
  3811. epoch,
  3812. room_id,
  3813. event_type,
  3814. self._canonical_json(payload),
  3815. self._now() if created_at is None else created_at,
  3816. ),
  3817. ).fetchone()["cursor"]
  3818. return int(cursor)
  3819. def _append_room_updated_summary(
  3820. self,
  3821. connection: sqlite3.Connection,
  3822. room_id: str,
  3823. *,
  3824. created_at: float,
  3825. ) -> None:
  3826. room = connection.execute(
  3827. """SELECT id, name, cwd, max_reply_rounds, created_at, updated_at, archived,
  3828. (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id)
  3829. AS agent_count
  3830. FROM group_rooms WHERE id = ? AND archived = 0""",
  3831. (room_id,),
  3832. ).fetchone()
  3833. if room is None:
  3834. raise GroupNotFoundError("Room not found")
  3835. self._append_event(
  3836. connection,
  3837. room_id,
  3838. "room.updated",
  3839. self._room_summary(room),
  3840. created_at=created_at,
  3841. )
  3842. def _room_detail(
  3843. self, connection: sqlite3.Connection, room_id: str, *, include_archived: bool
  3844. ) -> dict[str, object]:
  3845. room = connection.execute(
  3846. "SELECT * FROM group_rooms WHERE id = ?", (room_id,)
  3847. ).fetchone()
  3848. if room is None or (room["archived"] and not include_archived):
  3849. raise GroupNotFoundError("Room not found")
  3850. agents = connection.execute(
  3851. "SELECT * FROM group_agents WHERE room_id = ? ORDER BY created_at ASC, id ASC",
  3852. (room_id,),
  3853. ).fetchall()
  3854. result = self._room_wire(room)
  3855. result["agents"] = [self._agent_wire(agent) for agent in agents]
  3856. return result
  3857. def prepare_run_session_configuration(
  3858. self, run_id: str, configuration: Mapping[str, object]
  3859. ) -> bool:
  3860. """Detach a stale stored session before this claimed run is bound.
  3861. Configuration changes never interrupt the currently bound run. A later
  3862. claimed run reaches this method only after agent serialization, so it
  3863. can safely rotate the dormant stored session and rebuild full context.
  3864. """
  3865. canonical_run_id = self._canonical_uuid(run_id, "runId")
  3866. normalized = {
  3867. "model": configuration.get("model"),
  3868. "provider": configuration.get("provider"),
  3869. "reasoning_effort": configuration.get("reasoning_effort"),
  3870. "fast": configuration.get("fast"),
  3871. }
  3872. serialized = self._canonical_json(normalized)
  3873. with self.write_transaction() as connection:
  3874. run = self._run_row(connection, canonical_run_id)
  3875. if run["status"] != "running" or run["runtime_session_id"] is not None:
  3876. raise GroupConflictError("Run does not accept configuration rotation")
  3877. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  3878. if agent["session_config_json"] == serialized:
  3879. return False
  3880. now = self._now()
  3881. connection.execute(
  3882. """UPDATE group_agents
  3883. SET stored_session_id = NULL,
  3884. last_context_message_seq = 0,
  3885. session_config_json = ?,
  3886. updated_at = ?
  3887. WHERE id = ? AND room_id = ?""",
  3888. (serialized, now, agent["id"], run["room_id"]),
  3889. )
  3890. refreshed = self._owned_agent(connection, run["room_id"], run["agent_id"])
  3891. self._append_event(
  3892. connection,
  3893. run["room_id"],
  3894. "agent.updated",
  3895. self._agent_wire(refreshed),
  3896. created_at=now,
  3897. )
  3898. return True
  3899. def _active_room(self, connection: sqlite3.Connection, room_id: str) -> sqlite3.Row:
  3900. room = connection.execute(
  3901. "SELECT * FROM group_rooms WHERE id = ? AND archived = 0", (room_id,)
  3902. ).fetchone()
  3903. if room is None:
  3904. raise GroupNotFoundError("Room not found")
  3905. return room
  3906. def _owned_agent(
  3907. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  3908. ) -> sqlite3.Row:
  3909. agent = connection.execute(
  3910. "SELECT * FROM group_agents WHERE id = ? AND room_id = ?",
  3911. (agent_id, room_id),
  3912. ).fetchone()
  3913. if agent is None:
  3914. raise GroupNotFoundError("Agent not found in room")
  3915. return agent
  3916. def _enabled_agent(
  3917. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  3918. ) -> sqlite3.Row:
  3919. agent = self._owned_agent(connection, room_id, agent_id)
  3920. if not agent["enabled"]:
  3921. raise GroupConflictError("Agent is disabled")
  3922. return agent
  3923. @staticmethod
  3924. def _require_available_runtime(
  3925. connection: sqlite3.Connection, runtime_session_id: str, run_id: str
  3926. ) -> None:
  3927. occupied = connection.execute(
  3928. """SELECT id FROM group_agent_runs
  3929. WHERE runtime_session_id = ?
  3930. AND status IN ('running', 'awaiting_input')
  3931. AND id != ? LIMIT 1""",
  3932. (runtime_session_id, run_id),
  3933. ).fetchone()
  3934. if occupied is not None:
  3935. raise GroupConflictError("Runtime session is already in use")
  3936. def _agent_detail(
  3937. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  3938. ) -> dict[str, object]:
  3939. return self._agent_wire(self._owned_agent(connection, room_id, agent_id))
  3940. @staticmethod
  3941. def _message_row(connection: sqlite3.Connection, message_id: str) -> sqlite3.Row:
  3942. row = connection.execute(
  3943. "SELECT * FROM group_messages WHERE id = ?", (message_id,)
  3944. ).fetchone()
  3945. if row is None:
  3946. raise GroupNotFoundError("Message not found")
  3947. return row
  3948. @staticmethod
  3949. def _run_row(connection: sqlite3.Connection, run_id: str) -> sqlite3.Row:
  3950. row = connection.execute(
  3951. "SELECT * FROM group_agent_runs WHERE id = ?", (run_id,)
  3952. ).fetchone()
  3953. if row is None:
  3954. raise GroupNotFoundError("Run not found")
  3955. return row
  3956. @staticmethod
  3957. def _interaction_row(
  3958. connection: sqlite3.Connection, interaction_id: str
  3959. ) -> sqlite3.Row:
  3960. row = connection.execute(
  3961. "SELECT * FROM group_interactions WHERE id = ?", (interaction_id,)
  3962. ).fetchone()
  3963. if row is None:
  3964. raise GroupNotFoundError("Interaction not found")
  3965. return row
  3966. @classmethod
  3967. def _validate_run_message_state(
  3968. cls, run: sqlite3.Row, message: sqlite3.Row
  3969. ) -> None:
  3970. cls._validate_run_message_status(run["status"], message["status"])
  3971. @staticmethod
  3972. def _validate_run_message_status(run_status: str, message_status: str) -> None:
  3973. if message_status not in _MESSAGE_STATUSES_BY_RUN.get(run_status, frozenset()):
  3974. raise GroupConflictError("Run and response message states conflict")
  3975. def _update_run(
  3976. self,
  3977. connection: sqlite3.Connection,
  3978. run: sqlite3.Row,
  3979. status: str,
  3980. now: float,
  3981. runtime_session_id: object,
  3982. error: object,
  3983. ) -> dict[str, object]:
  3984. runtime = (
  3985. run["runtime_session_id"]
  3986. if runtime_session_id is UNSET
  3987. else runtime_session_id
  3988. )
  3989. run_error = run["error"] if error is UNSET else error
  3990. try:
  3991. connection.execute(
  3992. "UPDATE group_agent_runs SET status = ?, runtime_session_id = ?, error = ?, updated_at = ? WHERE id = ?",
  3993. (status, runtime, run_error, now, run["id"]),
  3994. )
  3995. except sqlite3.IntegrityError as conflict:
  3996. if "group_agent_runs.runtime_session_id" in str(conflict):
  3997. raise GroupConflictError(
  3998. "Runtime session is already in use"
  3999. ) from conflict
  4000. raise
  4001. return self._run_wire(self._run_row(connection, run["id"]))
  4002. @staticmethod
  4003. def _message_wire(row: sqlite3.Row) -> dict[str, object]:
  4004. try:
  4005. tool_state = GroupStore._load_json(row["tool_state_json"])
  4006. except (
  4007. TypeError,
  4008. ValueError,
  4009. UnicodeDecodeError,
  4010. json.JSONDecodeError,
  4011. ) as error:
  4012. raise GroupStoreError("Stored message tool state is corrupt") from error
  4013. if not isinstance(tool_state, list) or not all(
  4014. isinstance(item, dict) for item in tool_state
  4015. ):
  4016. raise GroupStoreError("Stored message tool state is corrupt")
  4017. return {
  4018. "seq": row["seq"],
  4019. "id": row["id"],
  4020. "roomId": row["room_id"],
  4021. "senderKind": row["sender_kind"],
  4022. "senderId": row["sender_id"],
  4023. "senderName": row["sender_name"],
  4024. "rootMessageId": row["root_message_id"],
  4025. "replyToMessageId": row["reply_to_message_id"],
  4026. "clientMessageId": row["client_message_id"],
  4027. "content": row["content"],
  4028. "reasoning": row["reasoning"],
  4029. "toolState": tool_state,
  4030. "status": row["status"],
  4031. "error": row["error"],
  4032. "visible": bool(row["visible"]),
  4033. "createdAt": row["created_at"],
  4034. "updatedAt": row["updated_at"],
  4035. }
  4036. @classmethod
  4037. def _projection_message(cls, row: sqlite3.Row) -> dict[str, object]:
  4038. try:
  4039. tool_state = cls._load_json(row["tool_state_json"])
  4040. except (
  4041. TypeError,
  4042. ValueError,
  4043. UnicodeDecodeError,
  4044. json.JSONDecodeError,
  4045. ) as error:
  4046. raise GroupStoreError("Stored message tool state is corrupt") from error
  4047. if not isinstance(tool_state, list) or not all(
  4048. isinstance(item, dict) for item in tool_state
  4049. ):
  4050. raise GroupStoreError("Stored message tool state is corrupt")
  4051. tool_names: list[str] = []
  4052. tool_names_truncated = False
  4053. for item in tool_state:
  4054. name = None
  4055. for key in ("name", "toolName"):
  4056. candidate = item.get(key)
  4057. if not isinstance(candidate, str) or not candidate:
  4058. continue
  4059. if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,119}", candidate) is None:
  4060. tool_names_truncated = True
  4061. continue
  4062. name = candidate
  4063. break
  4064. if name is None or name in tool_names:
  4065. continue
  4066. if len(tool_names) >= 16:
  4067. tool_names_truncated = True
  4068. break
  4069. tool_names.append(name)
  4070. return {
  4071. "seq": int(row["seq"]),
  4072. "senderKind": row["sender_kind"],
  4073. "senderId": row["sender_id"],
  4074. "senderName": row["sender_name"],
  4075. "content": row["content"],
  4076. "reasoning": row["reasoning"],
  4077. "toolNames": tool_names,
  4078. "status": row["status"],
  4079. "summary": row["error"],
  4080. "truncated": tool_names_truncated,
  4081. }
  4082. @classmethod
  4083. def _bound_projection_messages(
  4084. cls,
  4085. messages: list[dict[str, object]],
  4086. *,
  4087. omitted_count: int,
  4088. omitted_through_seq: int | None,
  4089. ) -> tuple[list[dict[str, object]], int, int | None, dict[str, object] | None]:
  4090. while len(messages) > 1:
  4091. omitted_summary = cls._projection_omitted_summary(
  4092. omitted_count, omitted_through_seq
  4093. )
  4094. if (
  4095. cls._projection_size(messages, omitted_summary)
  4096. <= CONTEXT_CHARACTER_BUDGET
  4097. ):
  4098. break
  4099. removed = messages.pop(0)
  4100. omitted_count += 1
  4101. omitted_through_seq = int(removed["seq"])
  4102. omitted_summary = cls._projection_omitted_summary(
  4103. omitted_count, omitted_through_seq
  4104. )
  4105. if (
  4106. messages
  4107. and cls._projection_size(messages, omitted_summary)
  4108. > CONTEXT_CHARACTER_BUDGET
  4109. ):
  4110. cls._truncate_projection_message(messages[0], omitted_summary)
  4111. if cls._projection_size(messages, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
  4112. raise GroupStoreError("Projection metadata exceeds the character budget")
  4113. return messages, omitted_count, omitted_through_seq, omitted_summary
  4114. @staticmethod
  4115. def _projection_omitted_summary(
  4116. count: int, through_seq: int | None
  4117. ) -> dict[str, object] | None:
  4118. if count == 0:
  4119. return None
  4120. if through_seq is None:
  4121. raise GroupStoreError("Projection omission metadata is corrupt")
  4122. return {
  4123. "messageCount": count,
  4124. "throughSeq": through_seq,
  4125. "text": f"Omitted {count} earlier messages through seq {through_seq}.",
  4126. }
  4127. @classmethod
  4128. def _projection_size(
  4129. cls,
  4130. messages: list[dict[str, object]],
  4131. omitted_summary: dict[str, object] | None,
  4132. ) -> int:
  4133. return len(
  4134. cls._canonical_json(
  4135. {"messages": messages, "omittedSummary": omitted_summary}
  4136. ).encode("utf-8")
  4137. )
  4138. @classmethod
  4139. def _truncate_projection_message(
  4140. cls,
  4141. message: dict[str, object],
  4142. omitted_summary: dict[str, object] | None,
  4143. ) -> None:
  4144. marker = "…[truncated]"
  4145. originals = {
  4146. field: message[field]
  4147. for field in ("content", "reasoning", "summary")
  4148. if isinstance(message[field], str) and message[field]
  4149. }
  4150. message["truncated"] = True
  4151. for field in originals:
  4152. message[field] = marker
  4153. wrapper = [message]
  4154. if cls._projection_size(wrapper, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
  4155. raise GroupStoreError("Projection identity exceeds the character budget")
  4156. for field in ("content", "reasoning", "summary"):
  4157. original = originals.get(field)
  4158. if original is None:
  4159. continue
  4160. low = 0
  4161. high = len(original)
  4162. while low < high:
  4163. candidate = (low + high + 1) // 2
  4164. message[field] = (
  4165. original
  4166. if candidate == len(original)
  4167. else f"{original[:candidate]}{marker}"
  4168. )
  4169. if (
  4170. cls._projection_size(wrapper, omitted_summary)
  4171. <= CONTEXT_CHARACTER_BUDGET
  4172. ):
  4173. low = candidate
  4174. else:
  4175. high = candidate - 1
  4176. message[field] = (
  4177. original if low == len(original) else f"{original[:low]}{marker}"
  4178. )
  4179. @staticmethod
  4180. def _run_wire(row: sqlite3.Row) -> dict[str, object]:
  4181. return {
  4182. "id": row["id"],
  4183. "roomId": row["room_id"],
  4184. "agentId": row["agent_id"],
  4185. "triggerMessageId": row["trigger_message_id"],
  4186. "responseMessageId": row["response_message_id"],
  4187. "rootMessageId": row["root_message_id"],
  4188. "depth": row["depth"],
  4189. "replyMode": row["reply_mode"],
  4190. "status": row["status"],
  4191. "runtimeSessionId": row["runtime_session_id"],
  4192. "error": row["error"],
  4193. "createdAt": row["created_at"],
  4194. "updatedAt": row["updated_at"],
  4195. }
  4196. @staticmethod
  4197. def _interaction_wire(row: sqlite3.Row) -> dict[str, object]:
  4198. try:
  4199. payload = GroupStore._load_json(row["payload_json"])
  4200. except (
  4201. TypeError,
  4202. ValueError,
  4203. UnicodeDecodeError,
  4204. json.JSONDecodeError,
  4205. ) as error:
  4206. raise GroupStoreError("Stored interaction payload is corrupt") from error
  4207. if not isinstance(payload, dict):
  4208. raise GroupStoreError("Stored interaction payload is corrupt")
  4209. return {
  4210. "id": row["id"],
  4211. "roomId": row["room_id"],
  4212. "agentId": row["agent_id"],
  4213. "runId": row["run_id"],
  4214. "kind": row["kind"],
  4215. "payload": payload,
  4216. "status": row["status"],
  4217. "createdAt": row["created_at"],
  4218. "resolvedAt": row["resolved_at"],
  4219. }
  4220. def _event_wire(self, row: sqlite3.Row, current_epoch: str) -> dict[str, object]:
  4221. try:
  4222. epoch = self._validated_epoch(row["epoch"])
  4223. payload = self._load_json(row["payload_json"])
  4224. except (
  4225. TypeError,
  4226. ValueError,
  4227. UnicodeDecodeError,
  4228. json.JSONDecodeError,
  4229. ) as error:
  4230. raise GroupStoreError("Stored event is corrupt") from error
  4231. if epoch != current_epoch or not isinstance(payload, dict):
  4232. raise GroupStoreError("Stored event is corrupt")
  4233. return {
  4234. "cursor": row["cursor"],
  4235. "epoch": epoch,
  4236. "roomId": row["room_id"],
  4237. "eventType": row["event_type"],
  4238. "payload": payload,
  4239. "createdAt": row["created_at"],
  4240. }
  4241. @staticmethod
  4242. def _message_text(
  4243. value: object, field: str, *, max_bytes: int, nonblank: bool = False
  4244. ) -> str:
  4245. if not isinstance(value, str):
  4246. raise ValueError(f"{field} must be a string")
  4247. try:
  4248. encoded = value.encode("utf-8")
  4249. except UnicodeEncodeError as error:
  4250. raise ValueError(f"{field} must be valid UTF-8") from error
  4251. if len(encoded) > max_bytes:
  4252. raise ValueError(f"{field} exceeds maximum size")
  4253. if nonblank and not value.strip():
  4254. raise ValueError(f"{field} must not be blank")
  4255. return value
  4256. @classmethod
  4257. def _mention_agent_ids(cls, value: object) -> list[str]:
  4258. if not isinstance(value, list):
  4259. raise ValueError("mentionAgentIds must be a list")
  4260. result = [
  4261. cls._canonical_uuid(agent_id, "mentionAgentIds") for agent_id in value
  4262. ]
  4263. if len(result) != len(set(result)):
  4264. raise GroupConflictError("mentionAgentIds must be unique")
  4265. return result
  4266. @staticmethod
  4267. def _interaction_id(value: object) -> str:
  4268. return normalize_interaction_id(value)
  4269. @staticmethod
  4270. def _runtime_session_id(value: object) -> str | None:
  4271. if value is None:
  4272. return None
  4273. if (
  4274. not isinstance(value, str)
  4275. or not value
  4276. or len(value) > 200
  4277. or any(unicodedata.category(character) == "Cc" for character in value)
  4278. ):
  4279. raise ValueError("runtimeSessionId is invalid")
  4280. return value
  4281. @classmethod
  4282. def _tool_state_json(cls, value: object) -> str:
  4283. if not isinstance(value, list):
  4284. raise ValueError("tool_state must be a list")
  4285. if not all(isinstance(item, Mapping) for item in value):
  4286. raise ValueError("tool_state entries must be objects")
  4287. encoded = cls._strict_json(value, "tool_state")
  4288. if len(encoded.encode("utf-8")) > MAX_TOOL_STATE_BYTES:
  4289. raise ValueError("tool_state exceeds maximum size")
  4290. return encoded
  4291. @classmethod
  4292. def _json_object(cls, value: object, field: str) -> str:
  4293. if not isinstance(value, Mapping):
  4294. raise ValueError(f"{field} must be an object")
  4295. encoded = cls._strict_json(dict(value), field)
  4296. if (
  4297. field == "payload"
  4298. and len(encoded.encode("utf-8")) > MAX_INTERACTION_PAYLOAD_BYTES
  4299. ):
  4300. raise ValueError("payload exceeds maximum size")
  4301. return encoded
  4302. @staticmethod
  4303. def _strict_json(value: object, field: str) -> str:
  4304. try:
  4305. encoded = json.dumps(
  4306. value,
  4307. ensure_ascii=False,
  4308. sort_keys=True,
  4309. separators=(",", ":"),
  4310. allow_nan=False,
  4311. )
  4312. encoded.encode("utf-8")
  4313. return encoded
  4314. except (TypeError, ValueError, UnicodeEncodeError) as error:
  4315. raise ValueError(f"{field} must be JSON-serializable") from error
  4316. @staticmethod
  4317. def _load_json(value: object) -> object:
  4318. if not isinstance(value, str):
  4319. raise ValueError("JSON must be a string")
  4320. return json.loads(
  4321. value,
  4322. parse_constant=lambda constant: (_ for _ in ()).throw(ValueError(constant)),
  4323. )
  4324. @staticmethod
  4325. def _page_limit(value: object, maximum: int, field: str) -> int:
  4326. if (
  4327. not isinstance(value, int)
  4328. or isinstance(value, bool)
  4329. or not 1 <= value <= maximum
  4330. ):
  4331. raise ValueError(f"{field} must be an integer from 1 to {maximum}")
  4332. return value
  4333. @staticmethod
  4334. def _positive_int(value: object, field: str) -> int:
  4335. if not isinstance(value, int) or isinstance(value, bool) or value < 1:
  4336. raise ValueError(f"{field} must be a positive integer")
  4337. return value
  4338. @staticmethod
  4339. def _nonnegative_int(value: object, field: str) -> int:
  4340. if not isinstance(value, int) or isinstance(value, bool) or value < 0:
  4341. raise ValueError(f"{field} must be a nonnegative integer")
  4342. return value
  4343. @staticmethod
  4344. def _finite_timestamp(value: object, field: str) -> float:
  4345. try:
  4346. finite = (
  4347. math.isfinite(value)
  4348. if isinstance(value, (int, float)) and not isinstance(value, bool)
  4349. else False
  4350. )
  4351. except OverflowError:
  4352. finite = False
  4353. if not finite:
  4354. raise ValueError(f"{field} must be finite")
  4355. return float(value)
  4356. def _new_agents(self, value: object) -> list[dict[str, object]]:
  4357. if not isinstance(value, list) or not 1 <= len(value) <= MAX_AGENTS_PER_ROOM:
  4358. raise ValueError(f"agents must contain 1 to {MAX_AGENTS_PER_ROOM} members")
  4359. agents = [self._new_agent(agent) for agent in value]
  4360. profiles = [agent["profile"] for agent in agents]
  4361. display_keys = [agent["display_name_key"] for agent in agents]
  4362. if len(profiles) != len(set(profiles)):
  4363. raise GroupConflictError("Agent profile must be unique within a room")
  4364. if len(display_keys) != len(set(display_keys)):
  4365. raise GroupConflictError("Agent display name must be unique within a room")
  4366. return agents
  4367. def _new_agent(self, command: object) -> dict[str, object]:
  4368. command = self._command(
  4369. command,
  4370. {
  4371. "profile", "displayName", "description", "replyWithoutMention",
  4372. "model", "provider", "reasoningEffort", "fastMode",
  4373. },
  4374. )
  4375. profile = self._profile(command.get("profile"))
  4376. raw_name = command.get("displayName")
  4377. explicit_name = (
  4378. raw_name.strip()
  4379. if isinstance(raw_name, str) and raw_name.strip()
  4380. else ""
  4381. )
  4382. display_name, display_name_key = normalize_display_name(
  4383. explicit_name or self._resolved_agent_name(profile) or profile
  4384. )
  4385. reply_without_mention = command.get("replyWithoutMention", False)
  4386. if not isinstance(reply_without_mention, bool):
  4387. raise ValueError("replyWithoutMention must be a boolean")
  4388. fast_mode = command.get("fastMode")
  4389. if fast_mode is not None and not isinstance(fast_mode, bool):
  4390. raise ValueError("fastMode must be a boolean or null")
  4391. if (command.get("model") is None) != (command.get("provider") is None):
  4392. raise ValueError("model and provider must both be set or both be null")
  4393. return {
  4394. "profile": profile,
  4395. "display_name": display_name,
  4396. "display_name_key": display_name_key,
  4397. "description": self._description(command.get("description", "")),
  4398. "reply_without_mention": reply_without_mention,
  4399. "model_override": self._agent_configuration_value(
  4400. command.get("model"), "model"
  4401. ),
  4402. "provider_override": self._agent_configuration_value(
  4403. command.get("provider"), "provider"
  4404. ),
  4405. "reasoning_effort_override": self._agent_configuration_value(
  4406. command.get("reasoningEffort"), "reasoningEffort"
  4407. ),
  4408. "fast_mode_override": fast_mode,
  4409. }
  4410. @staticmethod
  4411. def _agent_configuration_value(value: object, field: str) -> str | None:
  4412. if value is None:
  4413. return None
  4414. if not isinstance(value, str) or not value.strip():
  4415. raise ValueError(f"{field} must be a non-empty string or null")
  4416. normalized = value.strip()
  4417. if field == "reasoningEffort" and normalized not in {
  4418. "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
  4419. }:
  4420. raise ValueError("reasoningEffort is invalid")
  4421. return normalized
  4422. def _resolved_agent_name(self, profile: str) -> str:
  4423. try:
  4424. value = self._agent_name_resolver(profile)
  4425. except Exception as error:
  4426. raise GroupStoreError("Agent name settings could not be read") from error
  4427. if not isinstance(value, str):
  4428. raise GroupStoreError("Agent name settings are invalid")
  4429. normalized = value.strip()
  4430. return "" if is_reserved_mention_alias(normalized) else normalized
  4431. def _insert_agent(
  4432. self,
  4433. connection: sqlite3.Connection,
  4434. room_id: str,
  4435. agent: Mapping[str, object],
  4436. now: float,
  4437. ) -> str:
  4438. self._check_agent_conflicts(
  4439. connection, room_id, agent["display_name_key"], profile=agent["profile"]
  4440. )
  4441. agent_id = str(uuid.uuid4())
  4442. connection.execute(
  4443. """INSERT INTO group_agents
  4444. (id, room_id, profile, display_name, display_name_key, description,
  4445. reply_without_mention, model_override, provider_override,
  4446. reasoning_effort_override, fast_mode_override, created_at, updated_at)
  4447. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
  4448. (
  4449. agent_id,
  4450. room_id,
  4451. agent["profile"],
  4452. agent["display_name"],
  4453. agent["display_name_key"],
  4454. agent["description"],
  4455. int(bool(agent["reply_without_mention"])),
  4456. agent["model_override"],
  4457. agent["provider_override"],
  4458. agent["reasoning_effort_override"],
  4459. None if agent["fast_mode_override"] is None
  4460. else int(bool(agent["fast_mode_override"])),
  4461. now,
  4462. now,
  4463. ),
  4464. )
  4465. return agent_id
  4466. @staticmethod
  4467. def _check_agent_conflicts(
  4468. connection: sqlite3.Connection,
  4469. room_id: str,
  4470. display_name_key: str,
  4471. *,
  4472. profile: str | None = None,
  4473. exclude_agent_id: str | None = None,
  4474. ) -> None:
  4475. exclusion = " AND id != ?" if exclude_agent_id is not None else ""
  4476. suffix: tuple[object, ...] = (
  4477. (exclude_agent_id,) if exclude_agent_id is not None else ()
  4478. )
  4479. if (
  4480. profile is not None
  4481. and connection.execute(
  4482. f"SELECT 1 FROM group_agents WHERE room_id = ? AND profile = ?{exclusion}",
  4483. (room_id, profile, *suffix),
  4484. ).fetchone()
  4485. is not None
  4486. ):
  4487. raise GroupConflictError("Agent profile must be unique within a room")
  4488. if (
  4489. connection.execute(
  4490. f"SELECT 1 FROM group_agents WHERE room_id = ? AND display_name_key = ?{exclusion}",
  4491. (room_id, display_name_key, *suffix),
  4492. ).fetchone()
  4493. is not None
  4494. ):
  4495. raise GroupConflictError("Agent display name must be unique within a room")
  4496. @staticmethod
  4497. def _room_wire(row: sqlite3.Row) -> dict[str, object]:
  4498. return {
  4499. "id": row["id"],
  4500. "name": row["name"],
  4501. "cwd": row["cwd"],
  4502. "maxReplyRounds": row["max_reply_rounds"],
  4503. "createdAt": row["created_at"],
  4504. "updatedAt": row["updated_at"],
  4505. "archived": bool(row["archived"]),
  4506. }
  4507. @staticmethod
  4508. def _room_summary(row: sqlite3.Row) -> dict[str, object]:
  4509. return {
  4510. "id": row["id"],
  4511. "name": row["name"],
  4512. "cwd": row["cwd"],
  4513. "maxReplyRounds": row["max_reply_rounds"],
  4514. "createdAt": row["created_at"],
  4515. "updatedAt": row["updated_at"],
  4516. "archived": False,
  4517. "agentCount": row["agent_count"],
  4518. }
  4519. @staticmethod
  4520. def _agent_wire(row: sqlite3.Row) -> dict[str, object]:
  4521. return {
  4522. "id": row["id"],
  4523. "roomId": row["room_id"],
  4524. "profile": row["profile"],
  4525. "displayName": row["display_name"],
  4526. "description": row["description"],
  4527. "storedSessionId": row["stored_session_id"],
  4528. "lastContextMessageSeq": row["last_context_message_seq"],
  4529. "enabled": bool(row["enabled"]),
  4530. "replyWithoutMention": bool(row["reply_without_mention"]),
  4531. "model": row["model_override"],
  4532. "provider": row["provider_override"],
  4533. "reasoningEffort": row["reasoning_effort_override"],
  4534. "fastMode": None if row["fast_mode_override"] is None
  4535. else bool(row["fast_mode_override"]),
  4536. "createdAt": row["created_at"],
  4537. "updatedAt": row["updated_at"],
  4538. }
  4539. @staticmethod
  4540. def _canonical_uuid(value: object, field: str) -> str:
  4541. if not isinstance(value, str):
  4542. raise ValueError(f"{field} must be a canonical UUID")
  4543. try:
  4544. canonical = str(uuid.UUID(value))
  4545. except ValueError as error:
  4546. raise ValueError(f"{field} must be a canonical UUID") from error
  4547. if value != canonical:
  4548. raise ValueError(f"{field} must be a canonical UUID")
  4549. return canonical
  4550. @staticmethod
  4551. def _canonical_json(value: object) -> str:
  4552. try:
  4553. encoded = json.dumps(
  4554. value,
  4555. ensure_ascii=False,
  4556. sort_keys=True,
  4557. separators=(",", ":"),
  4558. allow_nan=False,
  4559. )
  4560. encoded.encode("utf-8")
  4561. return encoded
  4562. except (TypeError, ValueError, UnicodeEncodeError) as error:
  4563. raise ValueError("value must be strict JSON") from error
  4564. @classmethod
  4565. def _interaction_response_operation(
  4566. cls, value: object
  4567. ) -> tuple[str, str | None] | None:
  4568. if not isinstance(value, str):
  4569. return None
  4570. base, separator, interaction_id = value.partition(":")
  4571. operations = {
  4572. "interaction.approval.response": "approval",
  4573. "interaction.clarification.response": "clarification",
  4574. }
  4575. kind = operations.get(base)
  4576. if kind is None:
  4577. return None
  4578. if not separator:
  4579. return kind, None
  4580. try:
  4581. canonical_interaction_id = cls._interaction_id(interaction_id)
  4582. except ValueError:
  4583. return None
  4584. if canonical_interaction_id != interaction_id:
  4585. return None
  4586. return kind, canonical_interaction_id
  4587. @classmethod
  4588. def _interaction_operation(cls, kind: str, interaction_id: str) -> str:
  4589. if kind not in _INTERACTION_KINDS:
  4590. raise GroupStoreError("Stored interaction kind is corrupt")
  4591. canonical_interaction_id = cls._interaction_id(interaction_id)
  4592. if canonical_interaction_id != interaction_id:
  4593. raise GroupStoreError("Stored interaction identity is corrupt")
  4594. return f"interaction.{kind}.response:{canonical_interaction_id}"
  4595. @classmethod
  4596. def _idempotency_state(cls, value: object) -> dict[str, object]:
  4597. try:
  4598. state = cls._load_json(value)
  4599. except (TypeError, ValueError, json.JSONDecodeError) as error:
  4600. raise GroupStoreError("Stored interaction response is corrupt") from error
  4601. if not isinstance(state, dict) or cls._canonical_json(state) != value:
  4602. raise GroupStoreError("Stored interaction response is corrupt")
  4603. status = state.get("state")
  4604. if status == "claimed":
  4605. if (
  4606. not isinstance(state.get("interactionId"), str)
  4607. or state.get("kind") not in _INTERACTION_KINDS
  4608. ):
  4609. raise GroupStoreError("Stored interaction response is corrupt")
  4610. elif status == "completed":
  4611. if not isinstance(state.get("response"), dict):
  4612. raise GroupStoreError("Stored interaction response is corrupt")
  4613. interaction_status = state.get("interactionStatus", "resolved")
  4614. if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
  4615. raise GroupStoreError("Stored interaction response is corrupt")
  4616. elif status == "failed":
  4617. runtime_ids = state.get("runtimeSessionIds")
  4618. if (
  4619. not isinstance(state.get("reason"), str)
  4620. or not isinstance(runtime_ids, list)
  4621. or not all(isinstance(item, str) for item in runtime_ids)
  4622. or len(runtime_ids) != len(set(runtime_ids))
  4623. or not isinstance(state.get("run"), dict)
  4624. ):
  4625. raise GroupStoreError("Stored interaction response is corrupt")
  4626. else:
  4627. raise GroupStoreError("Stored interaction response is corrupt")
  4628. return state
  4629. @staticmethod
  4630. def _runtime_envelope(response: dict[str, object]) -> dict[str, object]:
  4631. if "result" not in response and "runtimeSessionIds" not in response:
  4632. return {"result": response, "runtimeSessionIds": []}
  4633. result = response.get("result")
  4634. runtime_ids = response.get("runtimeSessionIds")
  4635. if not isinstance(result, dict) or not isinstance(runtime_ids, list):
  4636. raise GroupStoreError("Stored lifecycle response is corrupt")
  4637. if not all(isinstance(value, str) for value in runtime_ids):
  4638. raise GroupStoreError("Stored lifecycle response is corrupt")
  4639. if len(runtime_ids) != len(set(runtime_ids)):
  4640. raise GroupStoreError("Stored lifecycle response is corrupt")
  4641. return {"result": result, "runtimeSessionIds": runtime_ids}
  4642. @staticmethod
  4643. def _scoped_payload(
  4644. command: Mapping[str, object], room_id: str, agent_id: str | None = None
  4645. ) -> dict[str, object]:
  4646. payload: dict[str, object] = {"body": dict(command), "roomId": room_id}
  4647. if agent_id is not None:
  4648. payload["agentId"] = agent_id
  4649. return payload
  4650. @staticmethod
  4651. def _integrity_conflict(error: sqlite3.IntegrityError) -> GroupStoreError:
  4652. message = str(error)
  4653. if "group_agents.room_id, group_agents.profile" in message:
  4654. return GroupConflictError("Agent profile must be unique within a room")
  4655. if "group_agents.room_id, group_agents.display_name_key" in message:
  4656. return GroupConflictError("Agent display name must be unique within a room")
  4657. if "group_messages.client_message_id" in message:
  4658. return GroupConflictError("clientMessageId already exists")
  4659. if "group_agent_runs.runtime_session_id" in message:
  4660. return GroupConflictError("Runtime session is already in use")
  4661. return GroupStoreError("Group storage constraint failed")
  4662. @staticmethod
  4663. def _command(value: object, allowed: set[str]) -> dict[str, object]:
  4664. if not isinstance(value, Mapping) or not all(
  4665. isinstance(key, str) for key in value
  4666. ):
  4667. raise ValueError("command must be an object")
  4668. unexpected = set(value) - allowed
  4669. if unexpected:
  4670. raise ValueError(
  4671. f"Unexpected command fields: {', '.join(sorted(unexpected))}"
  4672. )
  4673. return dict(value)
  4674. def _command_request_id(self, command: Mapping[str, object]) -> str:
  4675. if "requestId" not in command:
  4676. raise ValueError("requestId is required")
  4677. return self._canonical_uuid(command["requestId"], "requestId")
  4678. @staticmethod
  4679. def _string(command: Mapping[str, object], key: str) -> str:
  4680. value = command.get(key)
  4681. if not isinstance(value, str):
  4682. raise ValueError(f"{key} must be a string")
  4683. return value
  4684. @staticmethod
  4685. def _profile(value: object) -> str:
  4686. if not isinstance(value, str):
  4687. raise ValueError("profile must be a string")
  4688. profile = value.strip()
  4689. if not 1 <= len(profile) <= 100:
  4690. raise ValueError("profile must contain 1 to 100 characters")
  4691. return profile
  4692. @staticmethod
  4693. def _description(value: object) -> str:
  4694. if not isinstance(value, str):
  4695. raise ValueError("description must be a string")
  4696. description = value.strip()
  4697. if len(description) > 500:
  4698. raise ValueError("description must contain at most 500 characters")
  4699. return description
  4700. @staticmethod
  4701. def _now() -> float:
  4702. return time.time()
  4703. @staticmethod
  4704. def _encode_cursor(updated_at: float, room_id: str) -> str:
  4705. raw = json.dumps([updated_at, room_id], separators=(",", ":")).encode()
  4706. return base64.urlsafe_b64encode(raw).decode().rstrip("=")
  4707. @classmethod
  4708. def _decode_cursor(cls, cursor: str) -> tuple[float, str]:
  4709. if (
  4710. not isinstance(cursor, str)
  4711. or not cursor
  4712. or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
  4713. ):
  4714. raise ValueError("cursor is malformed")
  4715. try:
  4716. raw = base64.b64decode(
  4717. cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
  4718. )
  4719. decoded = json.loads(raw.decode("utf-8"))
  4720. if (
  4721. not isinstance(decoded, list)
  4722. or len(decoded) != 2
  4723. or isinstance(decoded[0], bool)
  4724. or not isinstance(decoded[0], (int, float))
  4725. or not math.isfinite(decoded[0])
  4726. ):
  4727. raise ValueError
  4728. updated_at = float(decoded[0])
  4729. room_id = cls._canonical_uuid(decoded[1], "cursor room id")
  4730. if cursor != cls._encode_cursor(updated_at, room_id):
  4731. raise ValueError
  4732. return updated_at, room_id
  4733. except (
  4734. ValueError,
  4735. TypeError,
  4736. UnicodeDecodeError,
  4737. json.JSONDecodeError,
  4738. binascii.Error,
  4739. OverflowError,
  4740. ) as error:
  4741. raise ValueError("cursor is malformed") from error