group_store.py 301 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169
  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_ROOM_INSTRUCTIONS_LENGTH,
  32. MAX_TOOL_STATE_BYTES,
  33. ORCHESTRATION_MODES,
  34. is_reserved_mention_alias,
  35. normalize_display_name,
  36. normalize_interaction_id,
  37. normalize_max_reply_rounds,
  38. normalize_room_cwd,
  39. normalize_room_instructions,
  40. normalize_room_name,
  41. )
  42. SCHEMA_VERSION = 12
  43. _WAL_RETRY_DELAYS = (0.01, 0.02, 0.04, 0.08)
  44. EVENT_RETENTION_SECONDS = 30 * 24 * 60 * 60
  45. MIN_RETAINED_EVENTS = 100_000
  46. UNSET = object()
  47. RUN_TRANSITIONS = {
  48. "queued": frozenset({"running", "interrupted", "failed"}),
  49. "running": frozenset({"awaiting_input", "completed", "failed", "interrupted"}),
  50. "awaiting_input": frozenset({"running", "failed", "interrupted"}),
  51. "completed": frozenset(),
  52. "failed": frozenset(),
  53. "interrupted": frozenset(),
  54. }
  55. _MESSAGE_STATUSES = frozenset(
  56. {"queued", "streaming", "completed", "failed", "interrupted"}
  57. )
  58. _AGENT_MESSAGE_STATUSES_BY_RUN = {
  59. "queued": frozenset({"queued"}),
  60. "running": frozenset({"queued", "streaming", "completed"}),
  61. "awaiting_input": frozenset({"queued", "streaming"}),
  62. "completed": frozenset(),
  63. "failed": frozenset(),
  64. "interrupted": frozenset(),
  65. }
  66. _AGENT_MESSAGE_TRANSITIONS = {
  67. "queued": frozenset({"queued", "streaming", "completed"}),
  68. "streaming": frozenset({"streaming", "completed"}),
  69. "completed": frozenset(),
  70. "failed": frozenset(),
  71. "interrupted": frozenset(),
  72. }
  73. _MESSAGE_STATUSES_BY_RUN = {
  74. "queued": frozenset({"queued"}),
  75. "running": frozenset({"queued", "streaming", "completed"}),
  76. "awaiting_input": frozenset({"queued", "streaming"}),
  77. "completed": frozenset({"completed"}),
  78. "failed": frozenset({"failed", "completed"}),
  79. "interrupted": frozenset({"interrupted", "completed"}),
  80. }
  81. _INTERACTION_KINDS = frozenset({"approval", "clarification"})
  82. _INTERACTION_TERMINAL_STATUSES = frozenset({"resolved", "cancelled"})
  83. _CASCADE_PENDING_OPERATION = "internal.cascade.pending"
  84. _CASCADE_COMPLETED_OPERATION = "internal.cascade.completed"
  85. _CASCADE_DISCARDED_OPERATION = "internal.cascade.discarded"
  86. _CASCADE_OPERATIONS = frozenset(
  87. {
  88. _CASCADE_PENDING_OPERATION,
  89. _CASCADE_COMPLETED_OPERATION,
  90. _CASCADE_DISCARDED_OPERATION,
  91. }
  92. )
  93. _CASCADE_PARSE_VERSION = 3
  94. _MAX_CASCADE_PAGE_SIZE = 32
  95. _MAX_CASCADE_PLAN_BYTES = 16 * 1024
  96. _HOST_FLOW_BARRIER_CONTENT = "internal.host-flow.parallel-barrier"
  97. _TOPIC_TITLE_LENGTH = 120
  98. _TOPIC_PREVIEW_LENGTH = 240
  99. _DEFAULT_SESSION_CONFIGURATION_JSON = (
  100. '{"fast":null,"model":null,"provider":null,"reasoning_effort":null}'
  101. )
  102. _SCHEMA_STATEMENTS = (
  103. """CREATE TABLE IF NOT EXISTS group_meta (
  104. key TEXT PRIMARY KEY,
  105. value TEXT NOT NULL
  106. )""",
  107. """CREATE TABLE IF NOT EXISTS group_rooms (
  108. id TEXT PRIMARY KEY,
  109. name TEXT NOT NULL,
  110. cwd TEXT NOT NULL DEFAULT '',
  111. instructions TEXT NOT NULL DEFAULT '',
  112. max_reply_rounds INTEGER NOT NULL DEFAULT 3,
  113. orchestration_mode TEXT NOT NULL DEFAULT 'free',
  114. created_at REAL NOT NULL,
  115. updated_at REAL NOT NULL,
  116. archived INTEGER NOT NULL DEFAULT 0
  117. )""",
  118. """CREATE TABLE IF NOT EXISTS group_topics (
  119. id TEXT PRIMARY KEY,
  120. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  121. title TEXT NOT NULL,
  122. last_read_message_seq INTEGER NOT NULL DEFAULT 0,
  123. created_at REAL NOT NULL,
  124. updated_at REAL NOT NULL,
  125. archived INTEGER NOT NULL DEFAULT 0,
  126. pinned INTEGER NOT NULL DEFAULT 0,
  127. UNIQUE(room_id, id)
  128. )""",
  129. """CREATE TABLE IF NOT EXISTS group_agents (
  130. id TEXT PRIMARY KEY,
  131. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  132. profile TEXT NOT NULL,
  133. display_name TEXT NOT NULL,
  134. display_name_key TEXT NOT NULL,
  135. description TEXT NOT NULL DEFAULT '',
  136. stored_session_id TEXT,
  137. last_context_message_seq INTEGER NOT NULL DEFAULT 0,
  138. enabled INTEGER NOT NULL DEFAULT 1,
  139. reply_without_mention INTEGER NOT NULL DEFAULT 0,
  140. is_host INTEGER NOT NULL DEFAULT 0,
  141. model_override TEXT,
  142. provider_override TEXT,
  143. reasoning_effort_override TEXT,
  144. fast_mode_override INTEGER,
  145. session_config_json TEXT,
  146. created_at REAL NOT NULL,
  147. updated_at REAL NOT NULL,
  148. UNIQUE(room_id, profile),
  149. UNIQUE(room_id, display_name_key)
  150. )""",
  151. """CREATE TABLE IF NOT EXISTS group_agent_topic_state (
  152. agent_id TEXT NOT NULL REFERENCES group_agents(id) ON DELETE CASCADE,
  153. topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
  154. last_context_message_seq INTEGER NOT NULL DEFAULT 0,
  155. created_at REAL NOT NULL,
  156. updated_at REAL NOT NULL,
  157. PRIMARY KEY(agent_id, topic_id)
  158. )""",
  159. """CREATE TABLE IF NOT EXISTS group_messages (
  160. seq INTEGER PRIMARY KEY AUTOINCREMENT,
  161. id TEXT NOT NULL UNIQUE,
  162. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  163. topic_id TEXT NOT NULL,
  164. sender_kind TEXT NOT NULL,
  165. sender_id TEXT NOT NULL,
  166. sender_name TEXT NOT NULL,
  167. root_message_id TEXT NOT NULL,
  168. reply_to_message_id TEXT,
  169. client_message_id TEXT UNIQUE,
  170. content TEXT NOT NULL DEFAULT '',
  171. reasoning TEXT NOT NULL DEFAULT '',
  172. tool_state_json TEXT NOT NULL DEFAULT '[]',
  173. status TEXT NOT NULL,
  174. error TEXT NOT NULL DEFAULT '',
  175. visible INTEGER NOT NULL DEFAULT 1,
  176. created_at REAL NOT NULL,
  177. updated_at REAL NOT NULL,
  178. FOREIGN KEY(room_id, topic_id)
  179. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  180. )""",
  181. """CREATE TABLE IF NOT EXISTS group_agent_runs (
  182. id TEXT PRIMARY KEY,
  183. room_id TEXT NOT NULL,
  184. topic_id TEXT NOT NULL,
  185. agent_id TEXT NOT NULL,
  186. trigger_message_id TEXT NOT NULL,
  187. response_message_id TEXT NOT NULL,
  188. root_message_id TEXT NOT NULL,
  189. depth INTEGER NOT NULL,
  190. reply_mode TEXT NOT NULL DEFAULT 'mentioned',
  191. required_reply INTEGER NOT NULL DEFAULT 0,
  192. status TEXT NOT NULL,
  193. runtime_session_id TEXT,
  194. requested_model TEXT,
  195. requested_provider TEXT,
  196. requested_reasoning_effort TEXT,
  197. requested_fast_mode INTEGER,
  198. actual_model TEXT,
  199. actual_provider TEXT,
  200. actual_reasoning_effort TEXT,
  201. actual_fast_mode INTEGER,
  202. error TEXT NOT NULL DEFAULT '',
  203. created_at REAL NOT NULL,
  204. updated_at REAL NOT NULL,
  205. FOREIGN KEY(room_id, topic_id)
  206. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  207. )""",
  208. """CREATE TABLE IF NOT EXISTS group_interactions (
  209. id TEXT PRIMARY KEY,
  210. room_id TEXT NOT NULL,
  211. topic_id TEXT NOT NULL,
  212. agent_id TEXT NOT NULL,
  213. run_id TEXT NOT NULL,
  214. kind TEXT NOT NULL,
  215. payload_json TEXT NOT NULL,
  216. status TEXT NOT NULL,
  217. created_at REAL NOT NULL,
  218. resolved_at REAL,
  219. FOREIGN KEY(room_id, topic_id)
  220. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  221. )""",
  222. """CREATE TABLE IF NOT EXISTS group_events (
  223. cursor INTEGER PRIMARY KEY AUTOINCREMENT,
  224. epoch TEXT NOT NULL,
  225. room_id TEXT,
  226. event_type TEXT NOT NULL,
  227. payload_json TEXT NOT NULL,
  228. created_at REAL NOT NULL
  229. )""",
  230. """CREATE TABLE IF NOT EXISTS group_idempotency (
  231. request_id TEXT PRIMARY KEY,
  232. operation TEXT NOT NULL,
  233. request_hash TEXT NOT NULL,
  234. response_json TEXT NOT NULL,
  235. created_at REAL NOT NULL
  236. )""",
  237. "CREATE INDEX IF NOT EXISTS idx_group_rooms_ordering ON group_rooms(archived, updated_at DESC, id DESC)",
  238. "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering ON group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)",
  239. "CREATE INDEX IF NOT EXISTS idx_group_messages_room_seq ON group_messages(room_id, seq)",
  240. "CREATE INDEX IF NOT EXISTS idx_group_messages_topic_seq ON group_messages(topic_id, seq)",
  241. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room ON group_agent_runs(room_id)",
  242. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_topic ON group_agent_runs(topic_id)",
  243. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_agent_status ON group_agent_runs(agent_id, status)",
  244. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room_status ON group_agent_runs(room_id, status)",
  245. "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_status_order ON group_agent_runs(status, created_at, id)",
  246. """CREATE UNIQUE INDEX IF NOT EXISTS idx_group_agents_room_host
  247. ON group_agents(room_id) WHERE is_host = 1""",
  248. """CREATE UNIQUE INDEX IF NOT EXISTS idx_group_agent_runs_active_runtime
  249. ON group_agent_runs(runtime_session_id)
  250. WHERE runtime_session_id IS NOT NULL
  251. AND status IN ('running', 'awaiting_input')""",
  252. "CREATE INDEX IF NOT EXISTS idx_group_interactions_room_agent ON group_interactions(room_id, agent_id)",
  253. "CREATE INDEX IF NOT EXISTS idx_group_interactions_topic ON group_interactions(topic_id)",
  254. "CREATE INDEX IF NOT EXISTS idx_group_interactions_run_status_kind ON group_interactions(run_id, status, kind)",
  255. "CREATE INDEX IF NOT EXISTS idx_group_events_room_created_at ON group_events(room_id, created_at)",
  256. "CREATE INDEX IF NOT EXISTS idx_group_events_created_at ON group_events(created_at)",
  257. "CREATE INDEX IF NOT EXISTS idx_group_idempotency_operation ON group_idempotency(operation)",
  258. )
  259. _EXPECTED_TABLES = frozenset(
  260. {
  261. "group_meta",
  262. "group_rooms",
  263. "group_topics",
  264. "group_agents",
  265. "group_agent_topic_state",
  266. "group_messages",
  267. "group_agent_runs",
  268. "group_interactions",
  269. "group_events",
  270. "group_idempotency",
  271. }
  272. )
  273. _LEGACY_TABLES = _EXPECTED_TABLES - {"group_topics", "group_agent_topic_state"}
  274. class GroupStoreError(RuntimeError):
  275. """Raised when the group-chat database is uninitialized or corrupt."""
  276. class GroupNotFoundError(GroupStoreError):
  277. """Raised when a room or agent is absent, or unavailable because it is archived."""
  278. class GroupConflictError(GroupStoreError):
  279. """Raised when a requested room-member invariant would be violated."""
  280. class IdempotencyConflict(GroupStoreError):
  281. """Raised when a request ID is reused for a different operation or payload."""
  282. @dataclass(frozen=True)
  283. class CursorPage:
  284. """A page of room summaries and the opaque cursor for its successor."""
  285. items: list[dict[str, object]]
  286. next_cursor: str | None
  287. class GroupStore:
  288. """The versioned SQLite authority for public group-chat state."""
  289. def __init__(
  290. self,
  291. path: Path,
  292. *,
  293. agent_name_resolver: Callable[[str], str] | None = None,
  294. ):
  295. self.path = Path(path)
  296. self._agent_name_resolver = agent_name_resolver or (lambda _profile: "")
  297. @classmethod
  298. def from_environment(
  299. cls, *, agent_name_resolver: Callable[[str], str] | None = None
  300. ) -> "GroupStore":
  301. hermes_home = Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
  302. return cls(
  303. hermes_home / "plugins" / "yaoyao" / "data" / "group-chat.db",
  304. agent_name_resolver=agent_name_resolver,
  305. )
  306. def connect(self) -> sqlite3.Connection:
  307. self.path.parent.mkdir(parents=True, exist_ok=True)
  308. connection = sqlite3.connect(self.path, timeout=5, isolation_level=None)
  309. connection.row_factory = sqlite3.Row
  310. connection.execute("PRAGMA foreign_keys = ON")
  311. connection.execute("PRAGMA busy_timeout = 5000")
  312. return connection
  313. @contextmanager
  314. def connection(self) -> Iterator[sqlite3.Connection]:
  315. """Yield a raw SQLite connection and always close it afterwards."""
  316. connection = self.connect()
  317. try:
  318. yield connection
  319. finally:
  320. connection.close()
  321. def initialize(self) -> None:
  322. """Create or validate the versioned schema without changing its epoch."""
  323. for attempt, delay in enumerate(_WAL_RETRY_DELAYS):
  324. try:
  325. self._initialize_once()
  326. return
  327. except sqlite3.OperationalError as error:
  328. if (
  329. not self._is_busy_or_locked(error)
  330. or attempt == len(_WAL_RETRY_DELAYS) - 1
  331. ):
  332. raise
  333. time.sleep(delay)
  334. def _initialize_once(self) -> None:
  335. with self.connection() as connection:
  336. connection.execute("PRAGMA journal_mode = WAL")
  337. connection.execute("BEGIN IMMEDIATE")
  338. try:
  339. table_names = self._user_table_names(connection)
  340. if not table_names:
  341. self._create_fresh_schema(connection)
  342. else:
  343. self._validate_existing_schema(connection, table_names)
  344. self._ensure_indexes(connection)
  345. self._sync_legacy_fallback_agent_names(connection)
  346. except Exception:
  347. connection.execute("ROLLBACK")
  348. raise
  349. else:
  350. connection.execute("COMMIT")
  351. def _sync_legacy_fallback_agent_names(
  352. self, connection: sqlite3.Connection
  353. ) -> None:
  354. """Adopt configured names for active legacy members without overriding edits."""
  355. rows = connection.execute(
  356. """SELECT group_agents.* FROM group_agents
  357. JOIN group_rooms ON group_rooms.id = group_agents.room_id
  358. WHERE group_agents.display_name = group_agents.profile
  359. AND group_rooms.archived = 0
  360. ORDER BY group_rooms.created_at ASC, group_rooms.id ASC,
  361. group_agents.created_at ASC, group_agents.id ASC"""
  362. ).fetchall()
  363. for row in rows:
  364. configured = self._resolved_agent_name(row["profile"])
  365. if not configured:
  366. continue
  367. try:
  368. display_name, display_name_key = normalize_display_name(configured)
  369. except ValueError:
  370. continue
  371. if (
  372. display_name == row["display_name"]
  373. and display_name_key == row["display_name_key"]
  374. ):
  375. continue
  376. conflict = connection.execute(
  377. """SELECT 1 FROM group_agents
  378. WHERE room_id = ? AND display_name_key = ? AND id != ?
  379. LIMIT 1""",
  380. (row["room_id"], display_name_key, row["id"]),
  381. ).fetchone()
  382. if conflict is not None:
  383. continue
  384. now = self._now()
  385. connection.execute(
  386. """UPDATE group_agents
  387. SET display_name = ?, display_name_key = ?, updated_at = ?
  388. WHERE id = ? AND room_id = ?""",
  389. (display_name, display_name_key, now, row["id"], row["room_id"]),
  390. )
  391. connection.execute(
  392. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  393. (now, row["room_id"]),
  394. )
  395. agent = self._agent_detail(connection, row["room_id"], row["id"])
  396. self._append_event(
  397. connection,
  398. row["room_id"],
  399. "agent.updated",
  400. agent,
  401. created_at=now,
  402. )
  403. self._append_room_updated_summary(
  404. connection, row["room_id"], created_at=now
  405. )
  406. def schema_version(self) -> int:
  407. value = self._metadata_value("schema_version")
  408. return self._validated_schema_version(value)
  409. def journal_epoch(self) -> str:
  410. value = self._metadata_value("journal_epoch")
  411. try:
  412. canonical = str(uuid.UUID(value))
  413. except (ValueError, AttributeError) as error:
  414. raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
  415. if value != canonical:
  416. raise GroupStoreError("GroupStore journal_epoch is corrupt")
  417. return canonical
  418. def _create_fresh_schema(self, connection: sqlite3.Connection) -> None:
  419. for statement in _SCHEMA_STATEMENTS:
  420. connection.execute(statement)
  421. connection.execute(
  422. "INSERT INTO group_meta(key, value) VALUES ('schema_version', ?)",
  423. (str(SCHEMA_VERSION),),
  424. )
  425. connection.execute(
  426. "INSERT INTO group_meta(key, value) VALUES ('journal_epoch', ?)",
  427. (str(uuid.uuid4()),),
  428. )
  429. def _validate_existing_schema(
  430. self, connection: sqlite3.Connection, table_names: set[str]
  431. ) -> None:
  432. if table_names not in {_EXPECTED_TABLES, _LEGACY_TABLES}:
  433. raise GroupStoreError("GroupStore schema is partial or corrupt")
  434. raw_version = self._metadata_value_from_connection(connection, "schema_version")
  435. if raw_version == "1":
  436. self._migrate_v1_to_v2(connection)
  437. raw_version = "2"
  438. if raw_version == "2":
  439. self._migrate_v2_to_v3(connection)
  440. raw_version = "3"
  441. if raw_version == "3":
  442. self._migrate_v3_to_v4(connection)
  443. raw_version = "4"
  444. if raw_version == "4":
  445. self._repair_early_v4(connection)
  446. self._migrate_v4_to_v5(connection)
  447. raw_version = "5"
  448. if raw_version == "5":
  449. self._migrate_v5_to_v6(connection)
  450. raw_version = "6"
  451. if raw_version == "6":
  452. self._migrate_v6_to_v7(connection)
  453. raw_version = "7"
  454. if raw_version == "7":
  455. self._migrate_v7_to_v8(connection)
  456. raw_version = "8"
  457. if raw_version == "8":
  458. self._migrate_v8_to_v9(connection)
  459. raw_version = "9"
  460. if raw_version == "9":
  461. self._migrate_v9_to_v10(connection)
  462. raw_version = "10"
  463. if raw_version == "10":
  464. self._migrate_v10_to_v11(connection)
  465. raw_version = "11"
  466. if raw_version == "11":
  467. self._migrate_v11_to_v12(connection)
  468. self._validated_schema_version(
  469. self._metadata_value_from_connection(connection, "schema_version")
  470. )
  471. self._validated_epoch(
  472. self._metadata_value_from_connection(connection, "journal_epoch")
  473. )
  474. self._validate_v8_columns(connection)
  475. self._validate_v7_values(connection)
  476. @staticmethod
  477. def _migrate_v1_to_v2(connection: sqlite3.Connection) -> None:
  478. connection.execute(
  479. "ALTER TABLE group_rooms ADD COLUMN max_reply_rounds INTEGER NOT NULL DEFAULT 3"
  480. )
  481. connection.execute(
  482. "ALTER TABLE group_agents ADD COLUMN reply_without_mention INTEGER NOT NULL DEFAULT 0"
  483. )
  484. connection.execute(
  485. "ALTER TABLE group_messages ADD COLUMN visible INTEGER NOT NULL DEFAULT 1"
  486. )
  487. connection.execute(
  488. "ALTER TABLE group_agent_runs ADD COLUMN reply_mode TEXT NOT NULL DEFAULT 'mentioned'"
  489. )
  490. connection.execute(
  491. "UPDATE group_meta SET value = '2' WHERE key = 'schema_version'"
  492. )
  493. @staticmethod
  494. def _migrate_v2_to_v3(connection: sqlite3.Connection) -> None:
  495. connection.execute("ALTER TABLE group_agents ADD COLUMN model_override TEXT")
  496. connection.execute("ALTER TABLE group_agents ADD COLUMN provider_override TEXT")
  497. connection.execute(
  498. "ALTER TABLE group_agents ADD COLUMN reasoning_effort_override TEXT"
  499. )
  500. connection.execute(
  501. "ALTER TABLE group_agents ADD COLUMN fast_mode_override INTEGER"
  502. )
  503. connection.execute(
  504. "ALTER TABLE group_agents ADD COLUMN session_config_json TEXT"
  505. )
  506. connection.execute(
  507. """UPDATE group_agents SET session_config_json = ?
  508. WHERE stored_session_id IS NOT NULL""",
  509. (_DEFAULT_SESSION_CONFIGURATION_JSON,),
  510. )
  511. connection.execute(
  512. "UPDATE group_meta SET value = '3' WHERE key = 'schema_version'"
  513. )
  514. @staticmethod
  515. def _migrate_v3_to_v4(connection: sqlite3.Connection) -> None:
  516. """Split legacy root chains into writable topics without touching rooms/Agents."""
  517. orphan_run = connection.execute(
  518. """SELECT run.id FROM group_agent_runs AS run
  519. LEFT JOIN group_messages AS trigger ON trigger.id = run.trigger_message_id
  520. LEFT JOIN group_messages AS response ON response.id = run.response_message_id
  521. WHERE trigger.id IS NULL OR response.id IS NULL LIMIT 1"""
  522. ).fetchone()
  523. if orphan_run is not None:
  524. raise GroupStoreError("GroupStore run messages are orphaned")
  525. orphan_interaction = connection.execute(
  526. """SELECT interaction.id FROM group_interactions AS interaction
  527. LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
  528. WHERE run.id IS NULL LIMIT 1"""
  529. ).fetchone()
  530. if orphan_interaction is not None:
  531. raise GroupStoreError("GroupStore interaction run is orphaned")
  532. connection.execute(
  533. """CREATE TABLE group_topics (
  534. id TEXT PRIMARY KEY,
  535. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  536. title TEXT NOT NULL,
  537. created_at REAL NOT NULL,
  538. updated_at REAL NOT NULL,
  539. UNIQUE(room_id, id)
  540. )"""
  541. )
  542. roots = connection.execute(
  543. """SELECT messages.room_id, messages.root_message_id,
  544. MIN(messages.created_at) AS created_at,
  545. COALESCE(
  546. MAX(CASE WHEN messages.visible = 1
  547. THEN messages.updated_at END),
  548. MAX(messages.updated_at)
  549. ) AS updated_at,
  550. COALESCE(
  551. (SELECT human.content FROM group_messages AS human
  552. WHERE human.room_id = messages.room_id
  553. AND human.root_message_id = messages.root_message_id
  554. AND human.sender_kind = 'human'
  555. ORDER BY human.seq ASC LIMIT 1),
  556. (SELECT visible.content FROM group_messages AS visible
  557. WHERE visible.room_id = messages.room_id
  558. AND visible.root_message_id = messages.root_message_id
  559. AND visible.visible = 1
  560. ORDER BY visible.seq ASC LIMIT 1),
  561. '话题'
  562. ) AS title
  563. FROM group_messages AS messages
  564. GROUP BY messages.room_id, messages.root_message_id
  565. ORDER BY MIN(messages.seq) ASC"""
  566. ).fetchall()
  567. for root in roots:
  568. title = " ".join(str(root["title"]).split()).strip()
  569. if not title:
  570. title = "话题"
  571. connection.execute(
  572. """INSERT INTO group_topics
  573. (id, room_id, title, created_at, updated_at)
  574. VALUES (?, ?, ?, ?, ?)""",
  575. (
  576. root["root_message_id"],
  577. root["room_id"],
  578. title[:_TOPIC_TITLE_LENGTH],
  579. root["created_at"],
  580. root["updated_at"],
  581. ),
  582. )
  583. connection.execute(
  584. """CREATE TABLE group_messages_v4 (
  585. seq INTEGER PRIMARY KEY AUTOINCREMENT,
  586. id TEXT NOT NULL UNIQUE,
  587. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  588. topic_id TEXT NOT NULL,
  589. sender_kind TEXT NOT NULL,
  590. sender_id TEXT NOT NULL,
  591. sender_name TEXT NOT NULL,
  592. root_message_id TEXT NOT NULL,
  593. reply_to_message_id TEXT,
  594. client_message_id TEXT UNIQUE,
  595. content TEXT NOT NULL DEFAULT '',
  596. reasoning TEXT NOT NULL DEFAULT '',
  597. tool_state_json TEXT NOT NULL DEFAULT '[]',
  598. status TEXT NOT NULL,
  599. error TEXT NOT NULL DEFAULT '',
  600. visible INTEGER NOT NULL DEFAULT 1,
  601. created_at REAL NOT NULL,
  602. updated_at REAL NOT NULL,
  603. FOREIGN KEY(room_id, topic_id)
  604. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  605. )"""
  606. )
  607. connection.execute(
  608. """INSERT INTO group_messages_v4
  609. (seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
  610. root_message_id, reply_to_message_id, client_message_id, content,
  611. reasoning, tool_state_json, status, error, visible, created_at, updated_at)
  612. SELECT seq, id, room_id, root_message_id, sender_kind, sender_id,
  613. sender_name, root_message_id, reply_to_message_id,
  614. client_message_id, content, reasoning, tool_state_json,
  615. status, error, visible, created_at, updated_at
  616. FROM group_messages ORDER BY seq ASC"""
  617. )
  618. connection.execute(
  619. """CREATE TABLE group_agent_runs_v4 (
  620. id TEXT PRIMARY KEY,
  621. room_id TEXT NOT NULL,
  622. topic_id TEXT NOT NULL,
  623. agent_id TEXT NOT NULL,
  624. trigger_message_id TEXT NOT NULL,
  625. response_message_id TEXT NOT NULL,
  626. root_message_id TEXT NOT NULL,
  627. depth INTEGER NOT NULL,
  628. reply_mode TEXT NOT NULL DEFAULT 'mentioned',
  629. status TEXT NOT NULL,
  630. runtime_session_id TEXT,
  631. error TEXT NOT NULL DEFAULT '',
  632. created_at REAL NOT NULL,
  633. updated_at REAL NOT NULL,
  634. FOREIGN KEY(room_id, topic_id)
  635. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  636. )"""
  637. )
  638. connection.execute(
  639. """INSERT INTO group_agent_runs_v4
  640. (id, room_id, topic_id, agent_id, trigger_message_id,
  641. response_message_id, root_message_id, depth, reply_mode, status,
  642. runtime_session_id, error, created_at, updated_at)
  643. SELECT id, room_id, root_message_id, agent_id, trigger_message_id,
  644. response_message_id, root_message_id, depth, reply_mode,
  645. status, runtime_session_id, error, created_at, updated_at
  646. FROM group_agent_runs"""
  647. )
  648. connection.execute(
  649. """CREATE TABLE group_interactions_v4 (
  650. id TEXT PRIMARY KEY,
  651. room_id TEXT NOT NULL,
  652. topic_id TEXT NOT NULL,
  653. agent_id TEXT NOT NULL,
  654. run_id TEXT NOT NULL,
  655. kind TEXT NOT NULL,
  656. payload_json TEXT NOT NULL,
  657. status TEXT NOT NULL,
  658. created_at REAL NOT NULL,
  659. resolved_at REAL,
  660. FOREIGN KEY(room_id, topic_id)
  661. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  662. )"""
  663. )
  664. connection.execute(
  665. """INSERT INTO group_interactions_v4
  666. (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
  667. status, created_at, resolved_at)
  668. SELECT interaction.id, interaction.room_id, run.topic_id,
  669. interaction.agent_id, interaction.run_id, interaction.kind,
  670. interaction.payload_json, interaction.status,
  671. interaction.created_at, interaction.resolved_at
  672. FROM group_interactions AS interaction
  673. JOIN group_agent_runs_v4 AS run ON run.id = interaction.run_id"""
  674. )
  675. connection.execute("DROP TABLE group_interactions")
  676. connection.execute("DROP TABLE group_agent_runs")
  677. connection.execute("DROP TABLE group_messages")
  678. connection.execute("ALTER TABLE group_messages_v4 RENAME TO group_messages")
  679. connection.execute(
  680. "ALTER TABLE group_agent_runs_v4 RENAME TO group_agent_runs"
  681. )
  682. connection.execute(
  683. "ALTER TABLE group_interactions_v4 RENAME TO group_interactions"
  684. )
  685. connection.execute(
  686. """CREATE TABLE group_agent_topic_state (
  687. agent_id TEXT NOT NULL REFERENCES group_agents(id) ON DELETE CASCADE,
  688. topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
  689. last_context_message_seq INTEGER NOT NULL DEFAULT 0,
  690. created_at REAL NOT NULL,
  691. updated_at REAL NOT NULL,
  692. PRIMARY KEY(agent_id, topic_id)
  693. )"""
  694. )
  695. connection.execute(
  696. """INSERT INTO group_agent_topic_state
  697. (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
  698. SELECT agent.id, topic.id,
  699. COALESCE((
  700. SELECT MAX(message.seq) FROM group_messages AS message
  701. WHERE message.topic_id = topic.id
  702. AND message.seq <= agent.last_context_message_seq
  703. ), 0),
  704. topic.created_at,
  705. CASE WHEN agent.updated_at > topic.updated_at
  706. THEN agent.updated_at ELSE topic.updated_at END
  707. FROM group_agents AS agent
  708. JOIN group_topics AS topic ON topic.room_id = agent.room_id"""
  709. )
  710. def add_topic_ids(value: object) -> object:
  711. if isinstance(value, list):
  712. return [add_topic_ids(item) for item in value]
  713. if not isinstance(value, dict):
  714. return value
  715. rewritten = {key: add_topic_ids(item) for key, item in value.items()}
  716. identity = rewritten.get("id")
  717. table: str | None = None
  718. if isinstance(identity, str):
  719. if "senderKind" in rewritten:
  720. table = "group_messages"
  721. elif "triggerMessageId" in rewritten:
  722. table = "group_agent_runs"
  723. elif "runId" in rewritten and "kind" in rewritten:
  724. table = "group_interactions"
  725. if table is not None and "topicId" not in rewritten:
  726. row = connection.execute(
  727. f"SELECT topic_id FROM {table} WHERE id = ?", (identity,)
  728. ).fetchone()
  729. if row is not None:
  730. rewritten["topicId"] = row["topic_id"]
  731. return rewritten
  732. for ledger in connection.execute(
  733. "SELECT request_id, operation, response_json FROM group_idempotency"
  734. ).fetchall():
  735. try:
  736. response = json.loads(ledger["response_json"])
  737. except (TypeError, ValueError, json.JSONDecodeError) as error:
  738. raise GroupStoreError("Stored idempotency response is corrupt") from error
  739. rewritten_value = add_topic_ids(response)
  740. if (
  741. GroupStore._interaction_response_operation(ledger["operation"])
  742. is not None
  743. and isinstance(rewritten_value, dict)
  744. and rewritten_value.get("state") == "failed"
  745. and isinstance(rewritten_value.get("run"), dict)
  746. ):
  747. rewritten_value["run"].pop("topicId", None)
  748. rewritten = GroupStore._canonical_json(rewritten_value)
  749. if rewritten != ledger["response_json"]:
  750. connection.execute(
  751. "UPDATE group_idempotency SET response_json = ? WHERE request_id = ?",
  752. (rewritten, ledger["request_id"]),
  753. )
  754. for event in connection.execute(
  755. """SELECT cursor, payload_json FROM group_events
  756. WHERE event_type IN ('message.upsert', 'run.updated',
  757. 'interaction.requested', 'interaction.resolved')"""
  758. ).fetchall():
  759. try:
  760. payload = json.loads(event["payload_json"])
  761. except (TypeError, ValueError, json.JSONDecodeError) as error:
  762. raise GroupStoreError("Stored event is corrupt") from error
  763. rewritten = GroupStore._canonical_json(add_topic_ids(payload))
  764. if rewritten != event["payload_json"]:
  765. connection.execute(
  766. "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
  767. (rewritten, event["cursor"]),
  768. )
  769. connection.execute(
  770. "UPDATE group_meta SET value = '4' WHERE key = 'schema_version'"
  771. )
  772. @staticmethod
  773. def _topic_foreign_key_kind(
  774. connection: sqlite3.Connection, table: str
  775. ) -> str:
  776. foreign_keys = list(connection.execute(f"PRAGMA foreign_key_list({table})"))
  777. grouped: dict[int, list[sqlite3.Row]] = {}
  778. for foreign_key in foreign_keys:
  779. grouped.setdefault(int(foreign_key["id"]), []).append(foreign_key)
  780. for foreign_key_rows in grouped.values():
  781. if foreign_key_rows[0]["table"] != "group_topics" or not all(
  782. row["on_delete"] == "CASCADE" for row in foreign_key_rows
  783. ):
  784. continue
  785. columns = [
  786. (row["from"], row["to"])
  787. for row in sorted(foreign_key_rows, key=lambda item: item["seq"])
  788. ]
  789. if columns == [("room_id", "room_id"), ("topic_id", "id")]:
  790. return "final"
  791. if columns == [("topic_id", "id")]:
  792. return "early"
  793. return "invalid"
  794. @classmethod
  795. def _repair_early_v4(cls, connection: sqlite3.Connection) -> None:
  796. """Upgrade the unpublished single-topic-FK v4 draft in one transaction."""
  797. tables = ("group_messages", "group_agent_runs", "group_interactions")
  798. foreign_key_kinds = {
  799. table: cls._topic_foreign_key_kind(connection, table) for table in tables
  800. }
  801. if all(kind == "final" for kind in foreign_key_kinds.values()):
  802. return
  803. if any(kind not in {"early", "final"} for kind in foreign_key_kinds.values()):
  804. raise GroupStoreError("GroupStore early v4 topic ownership is corrupt")
  805. invalid_queries = (
  806. """SELECT message.id FROM group_messages AS message
  807. LEFT JOIN group_topics AS topic ON topic.id = message.topic_id
  808. WHERE topic.id IS NULL OR topic.room_id != message.room_id LIMIT 1""",
  809. """SELECT run.id FROM group_agent_runs AS run
  810. LEFT JOIN group_topics AS topic ON topic.id = run.topic_id
  811. LEFT JOIN group_messages AS trigger
  812. ON trigger.id = run.trigger_message_id
  813. LEFT JOIN group_messages AS response
  814. ON response.id = run.response_message_id
  815. WHERE topic.id IS NULL OR topic.room_id != run.room_id
  816. OR trigger.id IS NULL OR response.id IS NULL
  817. OR trigger.room_id != run.room_id
  818. OR response.room_id != run.room_id
  819. OR trigger.topic_id != run.topic_id
  820. OR response.topic_id != run.topic_id
  821. LIMIT 1""",
  822. """SELECT interaction.id FROM group_interactions AS interaction
  823. LEFT JOIN group_topics AS topic ON topic.id = interaction.topic_id
  824. LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
  825. WHERE topic.id IS NULL OR topic.room_id != interaction.room_id
  826. OR run.id IS NULL OR run.room_id != interaction.room_id
  827. OR run.topic_id != interaction.topic_id
  828. LIMIT 1""",
  829. )
  830. if any(connection.execute(query).fetchone() is not None for query in invalid_queries):
  831. raise GroupStoreError("GroupStore early v4 ownership is corrupt")
  832. counts = {
  833. table: int(connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
  834. for table in tables
  835. }
  836. connection.execute(
  837. """CREATE TABLE group_messages_v4_repair (
  838. seq INTEGER PRIMARY KEY AUTOINCREMENT,
  839. id TEXT NOT NULL UNIQUE,
  840. room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
  841. topic_id TEXT NOT NULL,
  842. sender_kind TEXT NOT NULL,
  843. sender_id TEXT NOT NULL,
  844. sender_name TEXT NOT NULL,
  845. root_message_id TEXT NOT NULL,
  846. reply_to_message_id TEXT,
  847. client_message_id TEXT UNIQUE,
  848. content TEXT NOT NULL DEFAULT '',
  849. reasoning TEXT NOT NULL DEFAULT '',
  850. tool_state_json TEXT NOT NULL DEFAULT '[]',
  851. status TEXT NOT NULL,
  852. error TEXT NOT NULL DEFAULT '',
  853. visible INTEGER NOT NULL DEFAULT 1,
  854. created_at REAL NOT NULL,
  855. updated_at REAL NOT NULL,
  856. FOREIGN KEY(room_id, topic_id)
  857. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  858. )"""
  859. )
  860. connection.execute(
  861. """INSERT INTO group_messages_v4_repair
  862. (seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
  863. root_message_id, reply_to_message_id, client_message_id, content,
  864. reasoning, tool_state_json, status, error, visible, created_at, updated_at)
  865. SELECT seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
  866. root_message_id, reply_to_message_id, client_message_id, content,
  867. reasoning, tool_state_json, status, error, visible,
  868. created_at, updated_at
  869. FROM group_messages ORDER BY seq ASC"""
  870. )
  871. connection.execute(
  872. """CREATE TABLE group_agent_runs_v4_repair (
  873. id TEXT PRIMARY KEY,
  874. room_id TEXT NOT NULL,
  875. topic_id TEXT NOT NULL,
  876. agent_id TEXT NOT NULL,
  877. trigger_message_id TEXT NOT NULL,
  878. response_message_id TEXT NOT NULL,
  879. root_message_id TEXT NOT NULL,
  880. depth INTEGER NOT NULL,
  881. reply_mode TEXT NOT NULL DEFAULT 'mentioned',
  882. status TEXT NOT NULL,
  883. runtime_session_id TEXT,
  884. error TEXT NOT NULL DEFAULT '',
  885. created_at REAL NOT NULL,
  886. updated_at REAL NOT NULL,
  887. FOREIGN KEY(room_id, topic_id)
  888. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  889. )"""
  890. )
  891. connection.execute(
  892. """INSERT INTO group_agent_runs_v4_repair
  893. (id, room_id, topic_id, agent_id, trigger_message_id,
  894. response_message_id, root_message_id, depth, reply_mode, status,
  895. runtime_session_id, error, created_at, updated_at)
  896. SELECT id, room_id, topic_id, agent_id, trigger_message_id,
  897. response_message_id, root_message_id, depth, reply_mode,
  898. status, runtime_session_id, error, created_at, updated_at
  899. FROM group_agent_runs"""
  900. )
  901. connection.execute(
  902. """CREATE TABLE group_interactions_v4_repair (
  903. id TEXT PRIMARY KEY,
  904. room_id TEXT NOT NULL,
  905. topic_id TEXT NOT NULL,
  906. agent_id TEXT NOT NULL,
  907. run_id TEXT NOT NULL,
  908. kind TEXT NOT NULL,
  909. payload_json TEXT NOT NULL,
  910. status TEXT NOT NULL,
  911. created_at REAL NOT NULL,
  912. resolved_at REAL,
  913. FOREIGN KEY(room_id, topic_id)
  914. REFERENCES group_topics(room_id, id) ON DELETE CASCADE
  915. )"""
  916. )
  917. connection.execute(
  918. """INSERT INTO group_interactions_v4_repair
  919. (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
  920. status, created_at, resolved_at)
  921. SELECT id, room_id, topic_id, agent_id, run_id, kind, payload_json,
  922. status, created_at, resolved_at
  923. FROM group_interactions"""
  924. )
  925. connection.execute("DROP TABLE group_interactions")
  926. connection.execute("DROP TABLE group_agent_runs")
  927. connection.execute("DROP TABLE group_messages")
  928. connection.execute(
  929. "ALTER TABLE group_messages_v4_repair RENAME TO group_messages"
  930. )
  931. connection.execute(
  932. "ALTER TABLE group_agent_runs_v4_repair RENAME TO group_agent_runs"
  933. )
  934. connection.execute(
  935. "ALTER TABLE group_interactions_v4_repair RENAME TO group_interactions"
  936. )
  937. repaired_counts = {
  938. table: int(connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
  939. for table in tables
  940. }
  941. if repaired_counts != counts:
  942. raise GroupStoreError("GroupStore early v4 repair lost rows")
  943. for event in connection.execute(
  944. """SELECT cursor, payload_json FROM group_events
  945. WHERE event_type = 'agent.status'"""
  946. ).fetchall():
  947. try:
  948. payload = cls._load_json(event["payload_json"])
  949. except (TypeError, ValueError, json.JSONDecodeError) as error:
  950. raise GroupStoreError("Stored event is corrupt") from error
  951. if not isinstance(payload, dict):
  952. raise GroupStoreError("Stored event is corrupt")
  953. payload.pop("topicId", None)
  954. encoded = cls._canonical_json(payload)
  955. if encoded != event["payload_json"]:
  956. connection.execute(
  957. "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
  958. (encoded, event["cursor"]),
  959. )
  960. for ledger in connection.execute(
  961. "SELECT request_id, operation, response_json FROM group_idempotency"
  962. ).fetchall():
  963. if cls._interaction_response_operation(ledger["operation"]) is None:
  964. continue
  965. try:
  966. response = cls._load_json(ledger["response_json"])
  967. except (TypeError, ValueError, json.JSONDecodeError) as error:
  968. raise GroupStoreError("Stored interaction response is corrupt") from error
  969. if not isinstance(response, dict):
  970. raise GroupStoreError("Stored interaction response is corrupt")
  971. run = response.get("run")
  972. if response.get("state") != "failed" or not isinstance(run, dict):
  973. continue
  974. run.pop("topicId", None)
  975. encoded = cls._canonical_json(response)
  976. if encoded != ledger["response_json"]:
  977. connection.execute(
  978. """UPDATE group_idempotency SET response_json = ?
  979. WHERE request_id = ?""",
  980. (encoded, ledger["request_id"]),
  981. )
  982. connection.execute(
  983. """UPDATE group_topics AS topic
  984. SET updated_at = COALESCE(
  985. (SELECT MAX(message.updated_at) FROM group_messages AS message
  986. WHERE message.room_id = topic.room_id
  987. AND message.topic_id = topic.id AND message.visible = 1),
  988. (SELECT MAX(message.updated_at) FROM group_messages AS message
  989. WHERE message.room_id = topic.room_id
  990. AND message.topic_id = topic.id),
  991. topic.created_at
  992. )"""
  993. )
  994. @classmethod
  995. def _migrate_v4_to_v5(cls, connection: sqlite3.Connection) -> None:
  996. """Assign one durable host per room and freeze required-reply run state."""
  997. connection.execute(
  998. "ALTER TABLE group_agents ADD COLUMN is_host INTEGER NOT NULL DEFAULT 0"
  999. )
  1000. connection.execute(
  1001. """ALTER TABLE group_agent_runs
  1002. ADD COLUMN required_reply INTEGER NOT NULL DEFAULT 0"""
  1003. )
  1004. for room in connection.execute(
  1005. "SELECT id FROM group_rooms ORDER BY created_at ASC, id ASC"
  1006. ).fetchall():
  1007. host = connection.execute(
  1008. """SELECT id FROM group_agents WHERE room_id = ?
  1009. ORDER BY CASE
  1010. WHEN enabled = 1 AND reply_without_mention = 1 THEN 0
  1011. WHEN enabled = 1 THEN 1
  1012. ELSE 2
  1013. END, created_at ASC, id ASC
  1014. LIMIT 1""",
  1015. (room["id"],),
  1016. ).fetchone()
  1017. if host is None:
  1018. raise GroupStoreError("GroupStore room has no host candidate")
  1019. connection.execute(
  1020. "UPDATE group_agents SET is_host = 1 WHERE id = ? AND room_id = ?",
  1021. (host["id"], room["id"]),
  1022. )
  1023. def add_host_flags(value: object) -> object:
  1024. if isinstance(value, list):
  1025. return [add_host_flags(item) for item in value]
  1026. if not isinstance(value, dict):
  1027. return value
  1028. rewritten = {key: add_host_flags(item) for key, item in value.items()}
  1029. identity = rewritten.get("id")
  1030. room_id = rewritten.get("roomId")
  1031. if (
  1032. isinstance(identity, str)
  1033. and isinstance(room_id, str)
  1034. and {"profile", "displayName", "replyWithoutMention"}
  1035. <= rewritten.keys()
  1036. ):
  1037. agent = connection.execute(
  1038. "SELECT is_host FROM group_agents WHERE id = ? AND room_id = ?",
  1039. (identity, room_id),
  1040. ).fetchone()
  1041. rewritten["isHost"] = bool(agent["is_host"]) if agent else False
  1042. return rewritten
  1043. for ledger in connection.execute(
  1044. "SELECT request_id, response_json FROM group_idempotency"
  1045. ).fetchall():
  1046. try:
  1047. response = cls._load_json(ledger["response_json"])
  1048. except (TypeError, ValueError, json.JSONDecodeError) as error:
  1049. raise GroupStoreError("Stored idempotency response is corrupt") from error
  1050. rewritten = cls._canonical_json(add_host_flags(response))
  1051. if rewritten != ledger["response_json"]:
  1052. connection.execute(
  1053. """UPDATE group_idempotency SET response_json = ?
  1054. WHERE request_id = ?""",
  1055. (rewritten, ledger["request_id"]),
  1056. )
  1057. for event in connection.execute(
  1058. "SELECT cursor, payload_json FROM group_events"
  1059. ).fetchall():
  1060. try:
  1061. payload = cls._load_json(event["payload_json"])
  1062. except (TypeError, ValueError, json.JSONDecodeError) as error:
  1063. raise GroupStoreError("Stored event is corrupt") from error
  1064. rewritten = cls._canonical_json(add_host_flags(payload))
  1065. if rewritten != event["payload_json"]:
  1066. connection.execute(
  1067. "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
  1068. (rewritten, event["cursor"]),
  1069. )
  1070. connection.execute(
  1071. "UPDATE group_meta SET value = '5' WHERE key = 'schema_version'"
  1072. )
  1073. @staticmethod
  1074. def _migrate_v5_to_v6(connection: sqlite3.Connection) -> None:
  1075. """Add immutable configured and terminal effective model attribution."""
  1076. for column in (
  1077. "requested_model",
  1078. "requested_provider",
  1079. "actual_model",
  1080. "actual_provider",
  1081. ):
  1082. connection.execute(
  1083. f"ALTER TABLE group_agent_runs ADD COLUMN {column} TEXT"
  1084. )
  1085. connection.execute(
  1086. "UPDATE group_meta SET value = '6' WHERE key = 'schema_version'"
  1087. )
  1088. @staticmethod
  1089. def _migrate_v6_to_v7(connection: sqlite3.Connection) -> None:
  1090. """Add requested and effective reasoning/fast execution attribution."""
  1091. for definition in (
  1092. "requested_reasoning_effort TEXT",
  1093. "requested_fast_mode INTEGER",
  1094. "actual_reasoning_effort TEXT",
  1095. "actual_fast_mode INTEGER",
  1096. ):
  1097. connection.execute(
  1098. f"ALTER TABLE group_agent_runs ADD COLUMN {definition}"
  1099. )
  1100. connection.execute(
  1101. "UPDATE group_meta SET value = '7' WHERE key = 'schema_version'"
  1102. )
  1103. @staticmethod
  1104. def _migrate_v7_to_v8(connection: sqlite3.Connection) -> None:
  1105. """Add one monotonic human-read watermark to every topic."""
  1106. columns = {
  1107. str(row["name"])
  1108. for row in connection.execute("PRAGMA table_info(group_topics)")
  1109. }
  1110. if "last_read_message_seq" not in columns:
  1111. connection.execute(
  1112. """ALTER TABLE group_topics ADD COLUMN
  1113. last_read_message_seq INTEGER NOT NULL DEFAULT 0"""
  1114. )
  1115. connection.execute(
  1116. """UPDATE group_topics
  1117. SET last_read_message_seq = COALESCE((
  1118. SELECT MAX(message.seq) FROM group_messages AS message
  1119. WHERE message.topic_id = group_topics.id
  1120. AND message.visible = 1
  1121. ), 0)"""
  1122. )
  1123. connection.execute(
  1124. "UPDATE group_meta SET value = '8' WHERE key = 'schema_version'"
  1125. )
  1126. @staticmethod
  1127. def _migrate_v8_to_v9(connection: sqlite3.Connection) -> None:
  1128. """Make topics independently archivable without removing history."""
  1129. columns = {
  1130. str(row["name"])
  1131. for row in connection.execute("PRAGMA table_info(group_topics)")
  1132. }
  1133. if "archived" not in columns:
  1134. connection.execute(
  1135. "ALTER TABLE group_topics ADD COLUMN archived INTEGER NOT NULL DEFAULT 0"
  1136. )
  1137. connection.execute("DROP INDEX IF EXISTS idx_group_topics_room_ordering")
  1138. connection.execute(
  1139. "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering "
  1140. "ON group_topics(room_id, archived, updated_at DESC, id DESC)"
  1141. )
  1142. connection.execute(
  1143. "UPDATE group_meta SET value = '9' WHERE key = 'schema_version'"
  1144. )
  1145. @staticmethod
  1146. def _migrate_v9_to_v10(connection: sqlite3.Connection) -> None:
  1147. columns = {
  1148. str(row["name"])
  1149. for row in connection.execute("PRAGMA table_info(group_topics)")
  1150. }
  1151. if "pinned" not in columns:
  1152. connection.execute(
  1153. "ALTER TABLE group_topics ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0"
  1154. )
  1155. connection.execute("DROP INDEX IF EXISTS idx_group_topics_room_ordering")
  1156. connection.execute(
  1157. "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering "
  1158. "ON group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)"
  1159. )
  1160. connection.execute(
  1161. "UPDATE group_meta SET value = '10' WHERE key = 'schema_version'"
  1162. )
  1163. @staticmethod
  1164. def _migrate_v10_to_v11(connection: sqlite3.Connection) -> None:
  1165. columns = {
  1166. str(row["name"])
  1167. for row in connection.execute("PRAGMA table_info(group_rooms)")
  1168. }
  1169. if "orchestration_mode" not in columns:
  1170. connection.execute(
  1171. "ALTER TABLE group_rooms ADD COLUMN orchestration_mode "
  1172. "TEXT NOT NULL DEFAULT 'free'"
  1173. )
  1174. connection.execute(
  1175. "UPDATE group_meta SET value = '11' WHERE key = 'schema_version'"
  1176. )
  1177. @staticmethod
  1178. def _migrate_v11_to_v12(connection: sqlite3.Connection) -> None:
  1179. columns = {
  1180. str(row["name"])
  1181. for row in connection.execute("PRAGMA table_info(group_rooms)")
  1182. }
  1183. if "instructions" not in columns:
  1184. connection.execute(
  1185. "ALTER TABLE group_rooms ADD COLUMN instructions "
  1186. "TEXT NOT NULL DEFAULT ''"
  1187. )
  1188. connection.execute(
  1189. "UPDATE group_meta SET value = '12' WHERE key = 'schema_version'"
  1190. )
  1191. @staticmethod
  1192. def _validate_v8_columns(connection: sqlite3.Connection) -> None:
  1193. expected_columns = {
  1194. "group_meta": {"key", "value"},
  1195. "group_rooms": {"id", "name", "cwd", "instructions", "max_reply_rounds", "orchestration_mode", "created_at", "updated_at", "archived"},
  1196. "group_topics": {"id", "room_id", "title", "last_read_message_seq", "created_at", "updated_at", "archived", "pinned"},
  1197. "group_agents": {"id", "room_id", "profile", "display_name", "display_name_key", "description", "stored_session_id", "last_context_message_seq", "enabled", "reply_without_mention", "is_host", "model_override", "provider_override", "reasoning_effort_override", "fast_mode_override", "session_config_json", "created_at", "updated_at"},
  1198. "group_agent_topic_state": {"agent_id", "topic_id", "last_context_message_seq", "created_at", "updated_at"},
  1199. "group_messages": {"seq", "id", "room_id", "topic_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"},
  1200. "group_agent_runs": {"id", "room_id", "topic_id", "agent_id", "trigger_message_id", "response_message_id", "root_message_id", "depth", "reply_mode", "required_reply", "status", "runtime_session_id", "requested_model", "requested_provider", "requested_reasoning_effort", "requested_fast_mode", "actual_model", "actual_provider", "actual_reasoning_effort", "actual_fast_mode", "error", "created_at", "updated_at"},
  1201. "group_interactions": {"id", "room_id", "topic_id", "agent_id", "run_id", "kind", "payload_json", "status", "created_at", "resolved_at"},
  1202. "group_events": {"cursor", "epoch", "room_id", "event_type", "payload_json", "created_at"},
  1203. "group_idempotency": {"request_id", "operation", "request_hash", "response_json", "created_at"},
  1204. }
  1205. exact_specs = {
  1206. ("group_rooms", "max_reply_rounds"): ("INTEGER", 1, "3"),
  1207. ("group_rooms", "orchestration_mode"): ("TEXT", 1, "'free'"),
  1208. ("group_rooms", "instructions"): ("TEXT", 1, "''"),
  1209. ("group_agents", "reply_without_mention"): ("INTEGER", 1, "0"),
  1210. ("group_agents", "is_host"): ("INTEGER", 1, "0"),
  1211. ("group_messages", "visible"): ("INTEGER", 1, "1"),
  1212. ("group_agent_runs", "reply_mode"): ("TEXT", 1, "'mentioned'"),
  1213. ("group_agent_runs", "required_reply"): ("INTEGER", 1, "0"),
  1214. ("group_messages", "topic_id"): ("TEXT", 1, None),
  1215. ("group_agent_runs", "topic_id"): ("TEXT", 1, None),
  1216. ("group_interactions", "topic_id"): ("TEXT", 1, None),
  1217. ("group_agent_topic_state", "last_context_message_seq"): ("INTEGER", 1, "0"),
  1218. ("group_topics", "last_read_message_seq"): ("INTEGER", 1, "0"),
  1219. ("group_topics", "archived"): ("INTEGER", 1, "0"),
  1220. ("group_topics", "pinned"): ("INTEGER", 1, "0"),
  1221. }
  1222. for table, required in expected_columns.items():
  1223. rows = list(connection.execute(f"PRAGMA table_info({table})"))
  1224. columns = {row["name"]: row for row in rows}
  1225. if set(columns) != required:
  1226. raise GroupStoreError("GroupStore schema is partial or corrupt")
  1227. for (target_table, name), spec in exact_specs.items():
  1228. if target_table != table:
  1229. continue
  1230. row = columns[name]
  1231. actual = (str(row["type"]).upper(), int(row["notnull"]), row["dflt_value"])
  1232. if actual != spec:
  1233. raise GroupStoreError("GroupStore schema is partial or corrupt")
  1234. for table in ("group_messages", "group_agent_runs", "group_interactions"):
  1235. if GroupStore._topic_foreign_key_kind(connection, table) != "final":
  1236. raise GroupStoreError("GroupStore schema is partial or corrupt")
  1237. @staticmethod
  1238. def _validate_v7_values(connection: sqlite3.Connection) -> None:
  1239. invalid_value_queries = (
  1240. f"""SELECT 1 FROM group_rooms
  1241. WHERE typeof(max_reply_rounds) != 'integer'
  1242. OR (max_reply_rounds != -1 AND
  1243. (max_reply_rounds < 1 OR
  1244. max_reply_rounds > {MAX_FINITE_REPLY_ROUNDS}))
  1245. LIMIT 1""",
  1246. """SELECT 1 FROM group_rooms
  1247. WHERE typeof(orchestration_mode) != 'text'
  1248. OR orchestration_mode NOT IN ('free', 'host')
  1249. LIMIT 1""",
  1250. f"""SELECT 1 FROM group_rooms
  1251. WHERE typeof(instructions) != 'text'
  1252. OR length(instructions) > {MAX_ROOM_INSTRUCTIONS_LENGTH}
  1253. OR instr(instructions, char(13)) > 0
  1254. LIMIT 1""",
  1255. """SELECT 1 FROM group_agents
  1256. WHERE typeof(reply_without_mention) != 'integer'
  1257. OR reply_without_mention NOT IN (0, 1)
  1258. LIMIT 1""",
  1259. """SELECT 1 FROM group_agents
  1260. WHERE typeof(is_host) != 'integer' OR is_host NOT IN (0, 1)
  1261. LIMIT 1""",
  1262. """SELECT 1 FROM group_rooms AS room
  1263. LEFT JOIN group_agents AS agent ON agent.room_id = room.id
  1264. GROUP BY room.id
  1265. HAVING SUM(CASE WHEN agent.is_host = 1 THEN 1 ELSE 0 END) != 1
  1266. LIMIT 1""",
  1267. """SELECT 1 FROM group_agents AS host
  1268. WHERE host.is_host = 1 AND host.enabled = 0
  1269. AND EXISTS (
  1270. SELECT 1 FROM group_agents AS candidate
  1271. WHERE candidate.room_id = host.room_id
  1272. AND candidate.enabled = 1 AND candidate.id != host.id
  1273. )
  1274. LIMIT 1""",
  1275. """SELECT 1 FROM group_agents
  1276. WHERE fast_mode_override IS NOT NULL
  1277. AND (typeof(fast_mode_override) != 'integer'
  1278. OR fast_mode_override NOT IN (0, 1))
  1279. LIMIT 1""",
  1280. """SELECT 1 FROM group_agents
  1281. WHERE reasoning_effort_override IS NOT NULL
  1282. AND reasoning_effort_override NOT IN
  1283. ('none','minimal','low','medium','high','xhigh','max','ultra')
  1284. LIMIT 1""",
  1285. """SELECT 1 FROM group_messages
  1286. WHERE typeof(visible) != 'integer'
  1287. OR visible NOT IN (0, 1)
  1288. LIMIT 1""",
  1289. """SELECT 1 FROM group_agent_runs
  1290. WHERE typeof(reply_mode) != 'text'
  1291. OR reply_mode NOT IN ('mentioned', 'automatic')
  1292. LIMIT 1""",
  1293. """SELECT 1 FROM group_agent_runs
  1294. WHERE typeof(required_reply) != 'integer'
  1295. OR required_reply NOT IN (0, 1)
  1296. OR (required_reply = 1 AND reply_mode != 'automatic')
  1297. LIMIT 1""",
  1298. """SELECT 1 FROM group_agent_runs
  1299. WHERE (requested_model IS NULL) != (requested_provider IS NULL)
  1300. OR (actual_model IS NULL) != (actual_provider IS NULL)
  1301. OR length(COALESCE(requested_model, '')) > 4096
  1302. OR length(COALESCE(requested_provider, '')) > 4096
  1303. OR length(COALESCE(actual_model, '')) > 4096
  1304. OR length(COALESCE(actual_provider, '')) > 4096
  1305. LIMIT 1""",
  1306. """SELECT 1 FROM group_agent_runs
  1307. WHERE (requested_reasoning_effort IS NOT NULL
  1308. AND requested_reasoning_effort NOT IN
  1309. ('none','minimal','low','medium','high','xhigh','max','ultra'))
  1310. OR (actual_reasoning_effort IS NOT NULL
  1311. AND actual_reasoning_effort NOT IN
  1312. ('none','minimal','low','medium','high','xhigh','max','ultra'))
  1313. OR (requested_fast_mode IS NOT NULL
  1314. AND (typeof(requested_fast_mode) != 'integer'
  1315. OR requested_fast_mode NOT IN (0, 1)))
  1316. OR (actual_fast_mode IS NOT NULL
  1317. AND (typeof(actual_fast_mode) != 'integer'
  1318. OR actual_fast_mode NOT IN (0, 1)))
  1319. LIMIT 1""",
  1320. """SELECT 1 FROM group_agent_runs AS run
  1321. JOIN group_messages AS response
  1322. ON response.id = run.response_message_id
  1323. WHERE run.required_reply = 1 AND response.visible != 1
  1324. LIMIT 1""",
  1325. """SELECT 1 FROM group_agent_topic_state
  1326. WHERE typeof(last_context_message_seq) != 'integer'
  1327. OR last_context_message_seq < 0
  1328. LIMIT 1""",
  1329. """SELECT 1 FROM group_topics AS topic
  1330. WHERE typeof(topic.last_read_message_seq) != 'integer'
  1331. OR topic.last_read_message_seq < 0
  1332. OR topic.last_read_message_seq > COALESCE((
  1333. SELECT MAX(message.seq) FROM group_messages AS message
  1334. WHERE message.topic_id = topic.id
  1335. AND message.visible = 1
  1336. ), 0)
  1337. LIMIT 1""",
  1338. """SELECT 1 FROM group_messages AS message
  1339. LEFT JOIN group_topics AS topic ON topic.id = message.topic_id
  1340. WHERE topic.id IS NULL OR topic.room_id != message.room_id
  1341. LIMIT 1""",
  1342. """SELECT 1 FROM group_agent_runs AS run
  1343. LEFT JOIN group_topics AS topic ON topic.id = run.topic_id
  1344. LEFT JOIN group_messages AS trigger ON trigger.id = run.trigger_message_id
  1345. LEFT JOIN group_messages AS response ON response.id = run.response_message_id
  1346. WHERE topic.id IS NULL OR topic.room_id != run.room_id
  1347. OR trigger.id IS NULL OR response.id IS NULL
  1348. OR trigger.topic_id != run.topic_id
  1349. OR response.topic_id != run.topic_id
  1350. LIMIT 1""",
  1351. """SELECT 1 FROM group_interactions AS interaction
  1352. LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
  1353. WHERE run.id IS NULL OR interaction.topic_id != run.topic_id
  1354. OR interaction.room_id != run.room_id
  1355. LIMIT 1""",
  1356. """SELECT 1 FROM group_agent_topic_state AS state
  1357. LEFT JOIN group_agents AS agent ON agent.id = state.agent_id
  1358. LEFT JOIN group_topics AS topic ON topic.id = state.topic_id
  1359. WHERE agent.id IS NULL OR topic.id IS NULL
  1360. OR agent.room_id != topic.room_id
  1361. LIMIT 1""",
  1362. )
  1363. for query in invalid_value_queries:
  1364. if connection.execute(query).fetchone() is not None:
  1365. raise GroupStoreError("GroupStore stored values are corrupt")
  1366. for table, column in (
  1367. ("group_topics", "id"),
  1368. ("group_topics", "room_id"),
  1369. ("group_messages", "topic_id"),
  1370. ("group_agent_runs", "topic_id"),
  1371. ("group_interactions", "topic_id"),
  1372. ):
  1373. for row in connection.execute(f"SELECT {column} AS value FROM {table}"):
  1374. try:
  1375. canonical = str(uuid.UUID(row["value"]))
  1376. except (TypeError, ValueError, AttributeError) as error:
  1377. raise GroupStoreError("GroupStore stored values are corrupt") from error
  1378. if row["value"] != canonical:
  1379. raise GroupStoreError("GroupStore stored values are corrupt")
  1380. @staticmethod
  1381. def _ensure_indexes(connection: sqlite3.Connection) -> None:
  1382. """Repair v1 operational indexes without a schema-version migration."""
  1383. def canonical_index_sql(value: str) -> str:
  1384. without_guard = re.sub(
  1385. r"\bIF\s+NOT\s+EXISTS\b", "", value, flags=re.IGNORECASE
  1386. )
  1387. return " ".join(without_guard.split()).casefold()
  1388. indexes = {
  1389. "idx_group_rooms_ordering": (
  1390. [("archived", 0), ("updated_at", 1), ("id", 1)],
  1391. "group_rooms(archived, updated_at DESC, id DESC)",
  1392. ),
  1393. "idx_group_topics_room_ordering": (
  1394. [("room_id", 0), ("archived", 0), ("pinned", 1), ("updated_at", 1), ("id", 1)],
  1395. "group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)",
  1396. ),
  1397. "idx_group_messages_room_seq": (
  1398. [("room_id", 0), ("seq", 0)],
  1399. "group_messages(room_id, seq)",
  1400. ),
  1401. "idx_group_messages_topic_seq": (
  1402. [("topic_id", 0), ("seq", 0)],
  1403. "group_messages(topic_id, seq)",
  1404. ),
  1405. "idx_group_agent_runs_room": (
  1406. [("room_id", 0)],
  1407. "group_agent_runs(room_id)",
  1408. ),
  1409. "idx_group_agent_runs_topic": (
  1410. [("topic_id", 0)],
  1411. "group_agent_runs(topic_id)",
  1412. ),
  1413. "idx_group_agent_runs_agent_status": (
  1414. [("agent_id", 0), ("status", 0)],
  1415. "group_agent_runs(agent_id, status)",
  1416. ),
  1417. "idx_group_agent_runs_room_status": (
  1418. [("room_id", 0), ("status", 0)],
  1419. "group_agent_runs(room_id, status)",
  1420. ),
  1421. "idx_group_agent_runs_status_order": (
  1422. [("status", 0), ("created_at", 0), ("id", 0)],
  1423. "group_agent_runs(status, created_at, id)",
  1424. ),
  1425. "idx_group_idempotency_operation": (
  1426. [("operation", 0)],
  1427. "group_idempotency(operation)",
  1428. ),
  1429. "idx_group_interactions_run_status_kind": (
  1430. [("run_id", 0), ("status", 0), ("kind", 0)],
  1431. "group_interactions(run_id, status, kind)",
  1432. ),
  1433. "idx_group_interactions_room_agent": (
  1434. [("room_id", 0), ("agent_id", 0)],
  1435. "group_interactions(room_id, agent_id)",
  1436. ),
  1437. "idx_group_interactions_topic": (
  1438. [("topic_id", 0)],
  1439. "group_interactions(topic_id)",
  1440. ),
  1441. }
  1442. for name, (expected, definition) in indexes.items():
  1443. columns = [
  1444. (row["name"], row["desc"])
  1445. for row in connection.execute(f"PRAGMA index_xinfo({name})")
  1446. if row["key"]
  1447. ]
  1448. stored = connection.execute(
  1449. """SELECT sql FROM sqlite_master
  1450. WHERE type = 'index' AND name = ?""",
  1451. (name,),
  1452. ).fetchone()
  1453. expected_sql = canonical_index_sql(f"CREATE INDEX {name} ON {definition}")
  1454. stored_sql = (
  1455. None
  1456. if stored is None or stored["sql"] is None
  1457. else canonical_index_sql(stored["sql"])
  1458. )
  1459. if columns == expected and stored_sql == expected_sql:
  1460. continue
  1461. connection.execute(f"DROP INDEX IF EXISTS {name}")
  1462. connection.execute(f"CREATE INDEX {name} ON {definition}")
  1463. host_definition = """CREATE UNIQUE INDEX idx_group_agents_room_host
  1464. ON group_agents(room_id) WHERE is_host = 1"""
  1465. stored = connection.execute(
  1466. """SELECT sql FROM sqlite_master
  1467. WHERE type = 'index' AND name = ?""",
  1468. ("idx_group_agents_room_host",),
  1469. ).fetchone()
  1470. expected_sql = canonical_index_sql(host_definition)
  1471. stored_sql = (
  1472. None
  1473. if stored is None or stored["sql"] is None
  1474. else canonical_index_sql(stored["sql"])
  1475. )
  1476. if stored_sql != expected_sql:
  1477. connection.execute("DROP INDEX IF EXISTS idx_group_agents_room_host")
  1478. try:
  1479. connection.execute(host_definition)
  1480. except sqlite3.IntegrityError as error:
  1481. raise GroupStoreError("Room hosts are not unique") from error
  1482. active_runtime_definition = """CREATE UNIQUE INDEX
  1483. idx_group_agent_runs_active_runtime
  1484. ON group_agent_runs(runtime_session_id)
  1485. WHERE runtime_session_id IS NOT NULL
  1486. AND status IN ('running', 'awaiting_input')"""
  1487. stored = connection.execute(
  1488. """SELECT sql FROM sqlite_master
  1489. WHERE type = 'index' AND name = ?""",
  1490. ("idx_group_agent_runs_active_runtime",),
  1491. ).fetchone()
  1492. expected_sql = canonical_index_sql(active_runtime_definition)
  1493. stored_sql = (
  1494. None
  1495. if stored is None or stored["sql"] is None
  1496. else canonical_index_sql(stored["sql"])
  1497. )
  1498. if stored_sql == expected_sql:
  1499. return
  1500. connection.execute("DROP INDEX IF EXISTS idx_group_agent_runs_active_runtime")
  1501. try:
  1502. connection.execute(active_runtime_definition)
  1503. except sqlite3.IntegrityError as error:
  1504. raise GroupStoreError("Active runtime sessions are not unique") from error
  1505. @staticmethod
  1506. def _user_table_names(connection: sqlite3.Connection) -> set[str]:
  1507. return {
  1508. row["name"]
  1509. for row in connection.execute(
  1510. """SELECT name FROM sqlite_master
  1511. WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
  1512. )
  1513. }
  1514. @staticmethod
  1515. def _is_busy_or_locked(error: sqlite3.OperationalError) -> bool:
  1516. message = str(error).lower()
  1517. return "locked" in message or "busy" in message
  1518. @staticmethod
  1519. def _validated_schema_version(value: str) -> int:
  1520. try:
  1521. version = int(value)
  1522. except (TypeError, ValueError) as error:
  1523. raise GroupStoreError("GroupStore schema_version is corrupt") from error
  1524. if value != str(SCHEMA_VERSION) or version != SCHEMA_VERSION:
  1525. raise GroupStoreError("Unsupported or corrupt GroupStore schema_version")
  1526. return version
  1527. def _metadata_value(self, key: str) -> str:
  1528. try:
  1529. with self.connection() as connection:
  1530. return self._metadata_value_from_connection(connection, key)
  1531. except sqlite3.OperationalError as error:
  1532. raise GroupStoreError("GroupStore is not initialized") from error
  1533. @staticmethod
  1534. def _metadata_value_from_connection(
  1535. connection: sqlite3.Connection, key: str
  1536. ) -> str:
  1537. row = connection.execute(
  1538. "SELECT value FROM group_meta WHERE key = ?", (key,)
  1539. ).fetchone()
  1540. if row is None:
  1541. raise GroupStoreError(f"GroupStore metadata is missing {key}")
  1542. return row["value"]
  1543. @staticmethod
  1544. def _validated_epoch(value: str) -> str:
  1545. try:
  1546. canonical = str(uuid.UUID(value))
  1547. except (ValueError, AttributeError) as error:
  1548. raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
  1549. if value != canonical:
  1550. raise GroupStoreError("GroupStore journal_epoch is corrupt")
  1551. return canonical
  1552. @contextmanager
  1553. def read_transaction(self) -> Iterator[sqlite3.Connection]:
  1554. """Yield one consistent read snapshot and always close its connection."""
  1555. with self.connection() as connection:
  1556. connection.execute("BEGIN")
  1557. try:
  1558. yield connection
  1559. except Exception:
  1560. connection.execute("ROLLBACK")
  1561. raise
  1562. else:
  1563. connection.execute("COMMIT")
  1564. @contextmanager
  1565. def write_transaction(self) -> Iterator[sqlite3.Connection]:
  1566. """Yield one immediately-locked write transaction and always close it."""
  1567. with self.connection() as connection:
  1568. connection.execute("BEGIN IMMEDIATE")
  1569. try:
  1570. yield connection
  1571. except Exception:
  1572. connection.execute("ROLLBACK")
  1573. raise
  1574. else:
  1575. connection.execute("COMMIT")
  1576. def execute_idempotent(
  1577. self,
  1578. operation: str,
  1579. request_id: str,
  1580. payload: Mapping[str, object],
  1581. action: Callable[[sqlite3.Connection], dict[str, object]],
  1582. ) -> dict[str, object]:
  1583. """Execute a mutation exactly once for the canonical request and payload."""
  1584. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  1585. request_hash = hashlib.sha256(
  1586. self._canonical_json(payload).encode()
  1587. ).hexdigest()
  1588. try:
  1589. with self.write_transaction() as connection:
  1590. existing = connection.execute(
  1591. """SELECT operation, request_hash, response_json FROM group_idempotency
  1592. WHERE request_id = ?""",
  1593. (canonical_request_id,),
  1594. ).fetchone()
  1595. if existing is not None:
  1596. if (
  1597. existing["operation"] != operation
  1598. or existing["request_hash"] != request_hash
  1599. ):
  1600. raise IdempotencyConflict(
  1601. "requestId was already used for a different request"
  1602. )
  1603. stored_response = existing["response_json"]
  1604. try:
  1605. response = self._load_json(stored_response)
  1606. except (ValueError, json.JSONDecodeError, TypeError) as error:
  1607. raise GroupStoreError(
  1608. "Stored idempotency response is corrupt"
  1609. ) from error
  1610. if (
  1611. not isinstance(response, dict)
  1612. or self._canonical_json(response) != stored_response
  1613. ):
  1614. raise GroupStoreError("Stored idempotency response is corrupt")
  1615. return response
  1616. response = action(connection)
  1617. response_json = self._canonical_json(response)
  1618. connection.execute(
  1619. """INSERT INTO group_idempotency
  1620. (request_id, operation, request_hash, response_json, created_at)
  1621. VALUES (?, ?, ?, ?, ?)""",
  1622. (
  1623. canonical_request_id,
  1624. operation,
  1625. request_hash,
  1626. response_json,
  1627. self._now(),
  1628. ),
  1629. )
  1630. return response
  1631. except sqlite3.IntegrityError as error:
  1632. raise self._integrity_conflict(error) from error
  1633. def create_room(self, command: Mapping[str, object]) -> dict[str, object]:
  1634. command = self._command(
  1635. command,
  1636. {
  1637. "requestId",
  1638. "name",
  1639. "cwd",
  1640. "instructions",
  1641. "maxReplyRounds",
  1642. "orchestrationMode",
  1643. "agents",
  1644. },
  1645. )
  1646. request_id = self._command_request_id(command)
  1647. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1648. name = normalize_room_name(self._string(command, "name"))
  1649. cwd = normalize_room_cwd(self._string(command, "cwd"))
  1650. instructions = normalize_room_instructions(
  1651. command.get("instructions", "")
  1652. )
  1653. max_reply_rounds = normalize_max_reply_rounds(
  1654. command.get("maxReplyRounds", DEFAULT_MAX_REPLY_ROUNDS)
  1655. )
  1656. orchestration_mode = self._orchestration_mode(
  1657. command.get("orchestrationMode", "free")
  1658. )
  1659. agents = self._new_agents(command.get("agents"))
  1660. now = self._now()
  1661. room_id = str(uuid.uuid4())
  1662. connection.execute(
  1663. """INSERT INTO group_rooms
  1664. (id, name, cwd, instructions, max_reply_rounds, orchestration_mode,
  1665. created_at, updated_at, archived)
  1666. VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)""",
  1667. (
  1668. room_id, name, cwd, instructions, max_reply_rounds,
  1669. orchestration_mode, now, now,
  1670. ),
  1671. )
  1672. for agent in agents:
  1673. self._insert_agent(connection, room_id, agent, now)
  1674. room = self._room_detail(connection, room_id, include_archived=True)
  1675. self._append_event(
  1676. connection, room_id, "room.created", room, created_at=now
  1677. )
  1678. return room
  1679. return self.execute_idempotent("room.created", request_id, command, action)
  1680. def get_room(
  1681. self, room_id: str, *, include_archived: bool = False
  1682. ) -> dict[str, object]:
  1683. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1684. with self.read_transaction() as connection:
  1685. return self._room_detail(
  1686. connection, canonical_room_id, include_archived=include_archived
  1687. )
  1688. def room_snapshot(self, room_id: str) -> dict[str, object]:
  1689. """Read all state needed to recover one active room in one snapshot."""
  1690. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1691. with self.read_transaction() as connection:
  1692. result = self._room_detail(
  1693. connection, canonical_room_id, include_archived=False
  1694. )
  1695. run_rows = connection.execute(
  1696. """SELECT * FROM group_agent_runs
  1697. WHERE room_id = ? AND status IN ('queued', 'running', 'awaiting_input')
  1698. ORDER BY created_at ASC, id ASC""",
  1699. (canonical_room_id,),
  1700. ).fetchall()
  1701. interaction_rows = connection.execute(
  1702. """SELECT * FROM group_interactions
  1703. WHERE room_id = ? AND status = 'pending'
  1704. ORDER BY created_at ASC, id ASC""",
  1705. (canonical_room_id,),
  1706. ).fetchall()
  1707. cursor_row = connection.execute(
  1708. "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
  1709. ).fetchone()
  1710. status_priority = {
  1711. "queued": 1,
  1712. "running": 2,
  1713. "awaiting_input": 3,
  1714. }
  1715. statuses: dict[str, str] = {}
  1716. for run in run_rows:
  1717. previous = statuses.get(run["agent_id"], "idle")
  1718. if status_priority[run["status"]] > status_priority.get(previous, 0):
  1719. statuses[run["agent_id"]] = run["status"]
  1720. for agent in result["agents"]:
  1721. agent["status"] = statuses.get(agent["id"], "idle")
  1722. result["runs"] = [self._run_wire(row) for row in run_rows]
  1723. result["pendingInteractions"] = [
  1724. self._interaction_wire(row) for row in interaction_rows
  1725. ]
  1726. result["latestCursor"] = int(cursor_row["cursor"])
  1727. return result
  1728. def list_rooms(
  1729. self, *, limit: int, cursor: str | None, archived: bool = False
  1730. ) -> CursorPage:
  1731. if (
  1732. not isinstance(limit, int)
  1733. or isinstance(limit, bool)
  1734. or not 1 <= limit <= 100
  1735. ):
  1736. raise ValueError("limit must be an integer from 1 to 100")
  1737. cursor_values = self._decode_cursor(cursor) if cursor is not None else None
  1738. query = """SELECT id, name, cwd, instructions, max_reply_rounds, orchestration_mode,
  1739. created_at, updated_at, archived,
  1740. (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id) AS agent_count,
  1741. (SELECT COUNT(*) FROM group_topics WHERE room_id = group_rooms.id) AS topic_count
  1742. FROM group_rooms WHERE archived = ?"""
  1743. params: list[object] = [int(archived)]
  1744. if cursor_values is not None:
  1745. query += " AND ((updated_at < ?) OR (updated_at = ? AND id < ?))"
  1746. params.extend((cursor_values[0], cursor_values[0], cursor_values[1]))
  1747. query += " ORDER BY updated_at DESC, id DESC LIMIT ?"
  1748. params.append(limit + 1)
  1749. with self.connection() as connection:
  1750. rows = connection.execute(query, params).fetchall()
  1751. items = []
  1752. for row in rows[:limit]:
  1753. summary = self._room_summary(row)
  1754. activity = self._room_activity_from_connection(
  1755. connection, str(row["id"])
  1756. )
  1757. summary.update({
  1758. "activeRunCount": activity["activeRunCount"],
  1759. "unreadCount": activity["unreadCount"],
  1760. "lastMessage": activity["lastMessage"],
  1761. })
  1762. items.append(summary)
  1763. has_more = len(rows) > limit
  1764. next_cursor = None
  1765. if has_more and items:
  1766. last = rows[limit - 1]
  1767. next_cursor = self._encode_cursor(last["updated_at"], last["id"])
  1768. return CursorPage(items=items, next_cursor=next_cursor)
  1769. def list_topics(
  1770. self, room_id: str, *, limit: int, cursor: str | None,
  1771. archived: bool = False,
  1772. ) -> CursorPage:
  1773. """Return one room's topics in stable most-recently-active order."""
  1774. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1775. if (
  1776. not isinstance(limit, int)
  1777. or isinstance(limit, bool)
  1778. or not 1 <= limit <= 100
  1779. ):
  1780. raise ValueError("limit must be an integer from 1 to 100")
  1781. cursor_values = (
  1782. self._decode_topic_cursor(cursor, canonical_room_id)
  1783. if cursor is not None
  1784. else None
  1785. )
  1786. query = """SELECT topic.*,
  1787. (SELECT COUNT(*) FROM group_messages AS counted
  1788. WHERE counted.topic_id = topic.id AND counted.visible = 1)
  1789. AS message_count,
  1790. COALESCE((SELECT CASE WHEN TRIM(latest.content) != ''
  1791. THEN latest.content ELSE latest.error END
  1792. FROM group_messages AS latest
  1793. WHERE latest.topic_id = topic.id AND latest.visible = 1
  1794. AND (TRIM(latest.content) != '' OR TRIM(latest.error) != '')
  1795. ORDER BY latest.seq DESC LIMIT 1), '') AS preview,
  1796. (SELECT COUNT(*) FROM group_messages AS unread
  1797. WHERE unread.topic_id = topic.id AND unread.visible = 1
  1798. AND unread.sender_kind = 'agent'
  1799. AND (TRIM(unread.content) != '' OR TRIM(unread.error) != '')
  1800. AND unread.seq > topic.last_read_message_seq) AS unread_count,
  1801. COALESCE((SELECT MAX(visible_message.seq)
  1802. FROM group_messages AS visible_message
  1803. WHERE visible_message.topic_id = topic.id
  1804. AND visible_message.visible = 1), 0) AS latest_message_seq
  1805. FROM group_topics AS topic
  1806. WHERE topic.room_id = ? AND topic.archived = ?"""
  1807. params: list[object] = [canonical_room_id, int(archived)]
  1808. if cursor_values is not None:
  1809. query += " AND ((topic.updated_at < ?) OR (topic.updated_at = ? AND topic.id < ?))"
  1810. params.extend((cursor_values[0], cursor_values[0], cursor_values[1]))
  1811. query += " ORDER BY topic.pinned DESC, topic.updated_at DESC, topic.id DESC LIMIT ?"
  1812. params.append(limit + 1)
  1813. with self.read_transaction() as connection:
  1814. self._room_detail(connection, canonical_room_id, include_archived=True)
  1815. rows = connection.execute(query, params).fetchall()
  1816. has_more = len(rows) > limit
  1817. items = [self._topic_summary(row) for row in rows[:limit]]
  1818. next_cursor = None
  1819. if has_more and items:
  1820. last = rows[limit - 1]
  1821. next_cursor = self._encode_topic_cursor(
  1822. canonical_room_id, last["updated_at"], last["id"]
  1823. )
  1824. return CursorPage(items=items, next_cursor=next_cursor)
  1825. def list_pinned_topics(self, *, limit: int) -> CursorPage:
  1826. if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 100:
  1827. raise ValueError("limit must be an integer from 1 to 100")
  1828. with self.read_transaction() as connection:
  1829. rows = connection.execute(
  1830. """SELECT id, room_id FROM group_topics
  1831. WHERE archived = 0 AND pinned = 1
  1832. ORDER BY updated_at DESC, id DESC LIMIT ?""",
  1833. (limit,),
  1834. ).fetchall()
  1835. items = [self._topic_summary_by_id(connection, row["room_id"], row["id"])
  1836. for row in rows]
  1837. return CursorPage(items=items, next_cursor=None)
  1838. def room_activity(self, room_id: str) -> dict[str, object]:
  1839. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1840. with self.read_transaction() as connection:
  1841. self._room_detail(connection, canonical_room_id, include_archived=True)
  1842. return self._room_activity_from_connection(connection, canonical_room_id)
  1843. def _room_activity_from_connection(
  1844. self, connection: sqlite3.Connection, room_id: str
  1845. ) -> dict[str, object]:
  1846. counts = connection.execute(
  1847. """SELECT
  1848. (SELECT COUNT(*) FROM group_agent_runs AS run
  1849. WHERE run.room_id = ?
  1850. AND run.status IN ('queued', 'running', 'awaiting_input'))
  1851. AS active_run_count,
  1852. (SELECT COUNT(*) FROM group_messages AS message
  1853. JOIN group_topics AS topic ON topic.id = message.topic_id
  1854. WHERE message.room_id = ? AND message.visible = 1
  1855. AND message.sender_kind = 'agent'
  1856. AND (TRIM(message.content) != '' OR TRIM(message.error) != '')
  1857. AND message.seq > topic.last_read_message_seq)
  1858. AS unread_count""",
  1859. (room_id, room_id),
  1860. ).fetchone()
  1861. latest = connection.execute(
  1862. """SELECT id FROM group_messages
  1863. WHERE room_id = ? AND visible = 1
  1864. ORDER BY seq DESC LIMIT 1""",
  1865. (room_id,),
  1866. ).fetchone()
  1867. last_message = None
  1868. if latest is not None:
  1869. last_message = self._message_wire(
  1870. self._message_with_execution_row(connection, latest["id"])
  1871. )
  1872. return {
  1873. "roomId": room_id,
  1874. "activeRunCount": int(counts["active_run_count"]),
  1875. "unreadCount": int(counts["unread_count"]),
  1876. "lastMessage": last_message,
  1877. }
  1878. def update_room(
  1879. self, room_id: str, command: Mapping[str, object]
  1880. ) -> dict[str, object]:
  1881. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1882. command = self._command(
  1883. command,
  1884. {
  1885. "requestId", "name", "cwd", "instructions",
  1886. "maxReplyRounds", "orchestrationMode",
  1887. },
  1888. )
  1889. request_id = self._command_request_id(command)
  1890. changes = {
  1891. key
  1892. for key in (
  1893. "name", "cwd", "instructions", "maxReplyRounds", "orchestrationMode"
  1894. )
  1895. if key in command
  1896. }
  1897. if not changes:
  1898. raise ValueError(
  1899. "Room update requires name, cwd, instructions, maxReplyRounds, or orchestrationMode"
  1900. )
  1901. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1902. current_room = self._active_room(connection, canonical_room_id)
  1903. values: list[object] = []
  1904. assignments: list[str] = []
  1905. if "name" in changes:
  1906. assignments.append("name = ?")
  1907. values.append(normalize_room_name(self._string(command, "name")))
  1908. if "cwd" in changes:
  1909. assignments.append("cwd = ?")
  1910. values.append(normalize_room_cwd(self._string(command, "cwd")))
  1911. if "instructions" in changes:
  1912. assignments.append("instructions = ?")
  1913. values.append(normalize_room_instructions(command["instructions"]))
  1914. if "maxReplyRounds" in changes:
  1915. assignments.append("max_reply_rounds = ?")
  1916. values.append(normalize_max_reply_rounds(command["maxReplyRounds"]))
  1917. if "orchestrationMode" in changes:
  1918. next_mode = self._orchestration_mode(command["orchestrationMode"])
  1919. if next_mode != current_room["orchestration_mode"]:
  1920. active = connection.execute(
  1921. """SELECT 1 FROM group_agent_runs AS run
  1922. LEFT JOIN group_idempotency AS cascade
  1923. ON cascade.request_id = 'internal:cascade:' || run.id
  1924. WHERE run.room_id = ?
  1925. AND (
  1926. run.status IN ('queued', 'running', 'awaiting_input')
  1927. OR cascade.operation = ?
  1928. )
  1929. LIMIT 1""",
  1930. (canonical_room_id, _CASCADE_PENDING_OPERATION),
  1931. ).fetchone()
  1932. if active is not None:
  1933. raise GroupConflictError(
  1934. "Cannot change orchestration mode while runs are active"
  1935. )
  1936. assignments.append("orchestration_mode = ?")
  1937. values.append(next_mode)
  1938. assignments.append("updated_at = ?")
  1939. values.extend((self._now(), canonical_room_id))
  1940. connection.execute(
  1941. f"UPDATE group_rooms SET {', '.join(assignments)} WHERE id = ?", values
  1942. )
  1943. room = self._room_detail(
  1944. connection, canonical_room_id, include_archived=True
  1945. )
  1946. self._append_event(connection, canonical_room_id, "room.updated", room)
  1947. return room
  1948. return self.execute_idempotent(
  1949. "room.updated",
  1950. request_id,
  1951. self._scoped_payload(command, canonical_room_id),
  1952. action,
  1953. )
  1954. def update_topic(
  1955. self, room_id: str, topic_id: str, command: Mapping[str, object]
  1956. ) -> dict[str, object]:
  1957. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  1958. canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
  1959. command = self._command(command, {"requestId", "title", "pinned"})
  1960. request_id = self._command_request_id(command)
  1961. if not ({"title", "pinned"} & set(command)):
  1962. raise ValueError("Topic update requires title or pinned")
  1963. def action(connection: sqlite3.Connection) -> dict[str, object]:
  1964. self._active_room(connection, canonical_room_id)
  1965. self._active_topic(connection, canonical_room_id, canonical_topic_id)
  1966. assignments: list[str] = []
  1967. values: list[object] = []
  1968. if "title" in command:
  1969. assignments.append("title = ?")
  1970. values.append(self._topic_title(self._string(command, "title")))
  1971. if "pinned" in command:
  1972. if not isinstance(command["pinned"], bool):
  1973. raise ValueError("pinned must be a boolean")
  1974. assignments.append("pinned = ?")
  1975. values.append(int(command["pinned"]))
  1976. now = self._now()
  1977. assignments.append("updated_at = ?")
  1978. values.extend((now, canonical_topic_id, canonical_room_id))
  1979. connection.execute(
  1980. f"UPDATE group_topics SET {', '.join(assignments)} "
  1981. "WHERE id = ? AND room_id = ?",
  1982. values,
  1983. )
  1984. topic = self._topic_summary_by_id(
  1985. connection, canonical_room_id, canonical_topic_id
  1986. )
  1987. self._append_event(
  1988. connection, canonical_room_id, "topic.updated", topic,
  1989. created_at=now,
  1990. )
  1991. return topic
  1992. return self.execute_idempotent(
  1993. "topic.updated",
  1994. request_id,
  1995. self._scoped_payload(command, canonical_room_id, canonical_topic_id),
  1996. action,
  1997. )
  1998. def archive_topic(
  1999. self, room_id: str, topic_id: str, command: Mapping[str, object]
  2000. ) -> dict[str, object]:
  2001. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2002. canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
  2003. command = self._command(command, {"requestId"})
  2004. request_id = self._command_request_id(command)
  2005. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2006. self._active_room(connection, canonical_room_id)
  2007. self._active_topic(connection, canonical_room_id, canonical_topic_id)
  2008. now = self._now()
  2009. self._interrupt_runs_for_scope(
  2010. connection, room_id=canonical_room_id, topic_id=canonical_topic_id,
  2011. reason="Topic archived", now=now,
  2012. )
  2013. connection.execute(
  2014. "UPDATE group_topics SET archived = 1, updated_at = ? "
  2015. "WHERE id = ? AND room_id = ?",
  2016. (now, canonical_topic_id, canonical_room_id),
  2017. )
  2018. topic = self._topic_summary_by_id(
  2019. connection, canonical_room_id, canonical_topic_id
  2020. )
  2021. self._append_event(
  2022. connection, canonical_room_id, "topic.archived", topic,
  2023. created_at=now,
  2024. )
  2025. return topic
  2026. return self.execute_idempotent(
  2027. "topic.archived", request_id,
  2028. self._scoped_payload(command, canonical_room_id, canonical_topic_id),
  2029. action,
  2030. )
  2031. def restore_topic(
  2032. self, room_id: str, topic_id: str, command: Mapping[str, object]
  2033. ) -> dict[str, object]:
  2034. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2035. canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
  2036. command = self._command(command, {"requestId"})
  2037. request_id = self._command_request_id(command)
  2038. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2039. self._active_room(connection, canonical_room_id)
  2040. topic_row = self._topic_row(
  2041. connection, canonical_room_id, canonical_topic_id
  2042. )
  2043. if not topic_row["archived"]:
  2044. raise GroupConflictError("Topic is already active")
  2045. now = self._now()
  2046. connection.execute(
  2047. "UPDATE group_topics SET archived = 0, updated_at = ? "
  2048. "WHERE id = ? AND room_id = ?",
  2049. (now, canonical_topic_id, canonical_room_id),
  2050. )
  2051. topic = self._topic_summary_by_id(
  2052. connection, canonical_room_id, canonical_topic_id
  2053. )
  2054. self._append_event(
  2055. connection, canonical_room_id, "topic.restored", topic,
  2056. created_at=now,
  2057. )
  2058. return topic
  2059. return self.execute_idempotent(
  2060. "topic.restored", request_id,
  2061. self._scoped_payload(command, canonical_room_id, canonical_topic_id),
  2062. action,
  2063. )
  2064. def mark_topic_read(
  2065. self, room_id: str, topic_id: str, command: Mapping[str, object]
  2066. ) -> dict[str, object]:
  2067. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2068. canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
  2069. command = self._command(command, {"requestId", "throughSeq"})
  2070. request_id = self._command_request_id(command)
  2071. through_seq = self._nonnegative_int(command.get("throughSeq"), "throughSeq")
  2072. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2073. self._active_room(connection, canonical_room_id)
  2074. topic_row = self._topic_row(
  2075. connection, canonical_room_id, canonical_topic_id
  2076. )
  2077. maximum = int(connection.execute(
  2078. """SELECT COALESCE(MAX(seq), 0) FROM group_messages
  2079. WHERE room_id = ? AND topic_id = ? AND visible = 1""",
  2080. (canonical_room_id, canonical_topic_id),
  2081. ).fetchone()[0])
  2082. if through_seq > maximum:
  2083. raise ValueError("throughSeq exceeds the latest visible message")
  2084. changed = through_seq > int(topic_row["last_read_message_seq"])
  2085. if changed:
  2086. connection.execute(
  2087. """UPDATE group_topics SET last_read_message_seq = ?
  2088. WHERE id = ? AND room_id = ?""",
  2089. (through_seq, canonical_topic_id, canonical_room_id),
  2090. )
  2091. topic = self._topic_summary_by_id(
  2092. connection, canonical_room_id, canonical_topic_id
  2093. )
  2094. room = self._room_activity_from_connection(
  2095. connection, canonical_room_id
  2096. )
  2097. if changed:
  2098. now = self._now()
  2099. self._append_event(
  2100. connection, canonical_room_id, "topic.updated", topic,
  2101. created_at=now,
  2102. )
  2103. self._append_event(
  2104. connection, canonical_room_id, "room.activity", room,
  2105. created_at=now,
  2106. )
  2107. return {"topic": topic, "room": room}
  2108. return self.execute_idempotent(
  2109. "topic.read",
  2110. request_id,
  2111. self._scoped_payload(command, canonical_room_id, canonical_topic_id),
  2112. action,
  2113. )
  2114. def archive_room(
  2115. self, room_id: str, command: Mapping[str, object]
  2116. ) -> dict[str, object]:
  2117. return self.archive_room_with_runtime_targets(room_id, command)["result"]
  2118. def archive_room_with_runtime_targets(
  2119. self, room_id: str, command: Mapping[str, object]
  2120. ) -> dict[str, object]:
  2121. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2122. command = self._command(command, {"requestId"})
  2123. request_id = self._command_request_id(command)
  2124. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2125. self._active_room(connection, canonical_room_id)
  2126. now = self._now()
  2127. interrupted = self._interrupt_runs_for_scope(
  2128. connection,
  2129. room_id=canonical_room_id,
  2130. reason="Room archived",
  2131. now=now,
  2132. )
  2133. connection.execute(
  2134. "UPDATE group_rooms SET archived = 1, updated_at = ? WHERE id = ?",
  2135. (now, canonical_room_id),
  2136. )
  2137. room = self._room_detail(
  2138. connection, canonical_room_id, include_archived=True
  2139. )
  2140. self._append_event(
  2141. connection, canonical_room_id, "room.deleted", room, created_at=now
  2142. )
  2143. return {
  2144. "result": room,
  2145. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  2146. }
  2147. response = self.execute_idempotent(
  2148. "room.deleted",
  2149. request_id,
  2150. self._scoped_payload(command, canonical_room_id),
  2151. action,
  2152. )
  2153. return self._runtime_envelope(response)
  2154. def restore_room(self, room_id: str, command: Mapping[str, object]) -> dict[str, object]:
  2155. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2156. command = self._command(command, {"requestId"})
  2157. request_id = self._command_request_id(command)
  2158. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2159. room = self._room_detail(
  2160. connection, canonical_room_id, include_archived=True
  2161. )
  2162. if not room["archived"]:
  2163. raise GroupConflictError("Room is already active")
  2164. now = self._now()
  2165. connection.execute(
  2166. "UPDATE group_rooms SET archived = 0, updated_at = ? WHERE id = ?",
  2167. (now, canonical_room_id),
  2168. )
  2169. restored = self._room_detail(
  2170. connection, canonical_room_id, include_archived=True
  2171. )
  2172. self._append_event(
  2173. connection, canonical_room_id, "room.restored", restored,
  2174. created_at=now,
  2175. )
  2176. return restored
  2177. return self.execute_idempotent(
  2178. "room.restored", request_id,
  2179. self._scoped_payload(command, canonical_room_id), action,
  2180. )
  2181. def add_agent(
  2182. self, room_id: str, command: Mapping[str, object]
  2183. ) -> dict[str, object]:
  2184. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2185. command = self._command(
  2186. command,
  2187. {
  2188. "requestId",
  2189. "profile",
  2190. "displayName",
  2191. "description",
  2192. "replyWithoutMention",
  2193. "isHost",
  2194. "model",
  2195. "provider",
  2196. "reasoningEffort",
  2197. "fastMode",
  2198. },
  2199. )
  2200. request_id = self._command_request_id(command)
  2201. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2202. self._active_room(connection, canonical_room_id)
  2203. count = connection.execute(
  2204. "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
  2205. (canonical_room_id,),
  2206. ).fetchone()[0]
  2207. if count >= MAX_AGENTS_PER_ROOM:
  2208. raise GroupConflictError(
  2209. "Room has reached the maximum number of agents"
  2210. )
  2211. agent = self._new_agent(
  2212. {
  2213. key: command[key]
  2214. for key in (
  2215. "profile",
  2216. "displayName",
  2217. "description",
  2218. "replyWithoutMention",
  2219. "isHost",
  2220. "model",
  2221. "provider",
  2222. "reasoningEffort",
  2223. "fastMode",
  2224. )
  2225. if key in command
  2226. }
  2227. )
  2228. now = self._now()
  2229. requested_host = bool(agent["is_host"])
  2230. agent["is_host"] = False
  2231. agent_id = self._insert_agent(connection, canonical_room_id, agent, now)
  2232. current_host = self._room_host(connection, canonical_room_id)
  2233. switched: tuple[dict[str, object], dict[str, object]] | None = None
  2234. if requested_host or not bool(current_host["enabled"]):
  2235. switched = self._switch_host(
  2236. connection, canonical_room_id, agent_id, now=now
  2237. )
  2238. result = self._agent_detail(connection, canonical_room_id, agent_id)
  2239. connection.execute(
  2240. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  2241. (now, canonical_room_id),
  2242. )
  2243. if switched is not None:
  2244. self._append_event(
  2245. connection,
  2246. canonical_room_id,
  2247. "agent.updated",
  2248. switched[0],
  2249. created_at=now,
  2250. )
  2251. self._append_event(
  2252. connection,
  2253. canonical_room_id,
  2254. "agent.created",
  2255. result,
  2256. created_at=now,
  2257. )
  2258. self._append_room_updated_summary(
  2259. connection, canonical_room_id, created_at=now
  2260. )
  2261. return result
  2262. return self.execute_idempotent(
  2263. "agent.created",
  2264. request_id,
  2265. self._scoped_payload(command, canonical_room_id),
  2266. action,
  2267. )
  2268. def update_agent(
  2269. self, room_id: str, agent_id: str, command: Mapping[str, object]
  2270. ) -> dict[str, object]:
  2271. return self.update_agent_with_runtime_targets(room_id, agent_id, command)[
  2272. "result"
  2273. ]
  2274. def update_agent_with_runtime_targets(
  2275. self, room_id: str, agent_id: str, command: Mapping[str, object]
  2276. ) -> dict[str, object]:
  2277. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2278. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  2279. command = self._command(
  2280. command,
  2281. {
  2282. "requestId",
  2283. "displayName",
  2284. "description",
  2285. "enabled",
  2286. "replyWithoutMention",
  2287. "isHost",
  2288. "model",
  2289. "provider",
  2290. "reasoningEffort",
  2291. "fastMode",
  2292. },
  2293. )
  2294. request_id = self._command_request_id(command)
  2295. changes = {
  2296. key
  2297. for key in (
  2298. "displayName",
  2299. "description",
  2300. "enabled",
  2301. "replyWithoutMention",
  2302. "isHost",
  2303. "model",
  2304. "provider",
  2305. "reasoningEffort",
  2306. "fastMode",
  2307. )
  2308. if key in command
  2309. }
  2310. if not changes:
  2311. raise ValueError(
  2312. "Agent update requires a mutable agent field"
  2313. )
  2314. model_changes = changes & {"model", "provider"}
  2315. if model_changes and model_changes != {"model", "provider"}:
  2316. raise ValueError("model and provider must be updated together")
  2317. if model_changes and (
  2318. (command["model"] is None) != (command["provider"] is None)
  2319. ):
  2320. raise ValueError("model and provider must both be set or both be null")
  2321. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2322. self._active_room(connection, canonical_room_id)
  2323. previous = self._owned_agent(
  2324. connection, canonical_room_id, canonical_agent_id
  2325. )
  2326. requested_host = command.get("isHost")
  2327. if requested_host is not None and not isinstance(requested_host, bool):
  2328. raise ValueError("isHost must be a boolean")
  2329. if requested_host is False and bool(previous["is_host"]):
  2330. raise GroupConflictError(
  2331. "Current host cannot be cleared without selecting a replacement"
  2332. )
  2333. if requested_host is True and command.get("enabled") is False:
  2334. raise GroupConflictError("Host Agent must be enabled")
  2335. replacement_id: str | None = None
  2336. if (
  2337. bool(previous["is_host"])
  2338. and command.get("enabled") is False
  2339. and bool(previous["enabled"])
  2340. ):
  2341. replacement = self._first_enabled_host_candidate(
  2342. connection,
  2343. canonical_room_id,
  2344. exclude_agent_id=canonical_agent_id,
  2345. )
  2346. if replacement is None:
  2347. raise GroupConflictError(
  2348. "Host Agent cannot be disabled without an enabled replacement"
  2349. )
  2350. replacement_id = str(replacement["id"])
  2351. assignments: list[str] = []
  2352. values: list[object] = []
  2353. if "displayName" in changes:
  2354. raw_name = command.get("displayName")
  2355. configured = self._resolved_agent_name(previous["profile"])
  2356. effective = (
  2357. raw_name.strip()
  2358. if isinstance(raw_name, str) and raw_name.strip()
  2359. else configured or previous["profile"]
  2360. )
  2361. display_name, display_key = normalize_display_name(effective)
  2362. self._check_agent_conflicts(
  2363. connection,
  2364. canonical_room_id,
  2365. display_key,
  2366. exclude_agent_id=canonical_agent_id,
  2367. )
  2368. assignments.extend(("display_name = ?", "display_name_key = ?"))
  2369. values.extend((display_name, display_key))
  2370. if "description" in changes:
  2371. assignments.append("description = ?")
  2372. values.append(self._description(command.get("description")))
  2373. if "enabled" in changes:
  2374. enabled = command["enabled"]
  2375. if not isinstance(enabled, bool):
  2376. raise ValueError("enabled must be a boolean")
  2377. assignments.append("enabled = ?")
  2378. values.append(int(enabled))
  2379. if "replyWithoutMention" in changes:
  2380. reply_without_mention = command["replyWithoutMention"]
  2381. if not isinstance(reply_without_mention, bool):
  2382. raise ValueError("replyWithoutMention must be a boolean")
  2383. assignments.append("reply_without_mention = ?")
  2384. values.append(int(reply_without_mention))
  2385. configuration_columns = {
  2386. "model": "model_override",
  2387. "provider": "provider_override",
  2388. "reasoningEffort": "reasoning_effort_override",
  2389. }
  2390. for key, column in configuration_columns.items():
  2391. if key in changes:
  2392. assignments.append(f"{column} = ?")
  2393. values.append(self._agent_configuration_value(command[key], key))
  2394. if "fastMode" in changes:
  2395. fast_mode = command["fastMode"]
  2396. if fast_mode is not None and not isinstance(fast_mode, bool):
  2397. raise ValueError("fastMode must be a boolean or null")
  2398. assignments.append("fast_mode_override = ?")
  2399. values.append(None if fast_mode is None else int(fast_mode))
  2400. if changes & {"model", "provider", "reasoningEffort", "fastMode"}:
  2401. # The active run keeps its current session. The next scheduler
  2402. # pass sees this stale marker and rotates before submitting.
  2403. assignments.append("session_config_json = NULL")
  2404. now = self._now()
  2405. interrupted = {"runIds": [], "runtimeSessionIds": []}
  2406. if (
  2407. "enabled" in changes
  2408. and bool(previous["enabled"])
  2409. and command["enabled"] is False
  2410. ):
  2411. interrupted = self._interrupt_runs_for_scope(
  2412. connection,
  2413. room_id=canonical_room_id,
  2414. agent_id=canonical_agent_id,
  2415. reason="Agent disabled",
  2416. now=now,
  2417. )
  2418. assignments.append("updated_at = ?")
  2419. values.extend((now, canonical_agent_id, canonical_room_id))
  2420. connection.execute(
  2421. f"UPDATE group_agents SET {', '.join(assignments)} WHERE id = ? AND room_id = ?",
  2422. values,
  2423. )
  2424. switched: tuple[dict[str, object], dict[str, object]] | None = None
  2425. if replacement_id is not None:
  2426. switched = self._switch_host(
  2427. connection, canonical_room_id, replacement_id, now=now
  2428. )
  2429. elif requested_host is True:
  2430. switched = self._switch_host(
  2431. connection, canonical_room_id, canonical_agent_id, now=now
  2432. )
  2433. elif command.get("enabled") is True:
  2434. current_host = self._room_host(connection, canonical_room_id)
  2435. if not bool(current_host["enabled"]):
  2436. switched = self._switch_host(
  2437. connection, canonical_room_id, canonical_agent_id, now=now
  2438. )
  2439. connection.execute(
  2440. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  2441. (now, canonical_room_id),
  2442. )
  2443. result = self._agent_detail(
  2444. connection, canonical_room_id, canonical_agent_id
  2445. )
  2446. if switched is None:
  2447. self._append_event(
  2448. connection,
  2449. canonical_room_id,
  2450. "agent.updated",
  2451. result,
  2452. created_at=now,
  2453. )
  2454. else:
  2455. self._append_event(
  2456. connection,
  2457. canonical_room_id,
  2458. "agent.updated",
  2459. switched[0],
  2460. created_at=now,
  2461. )
  2462. self._append_event(
  2463. connection,
  2464. canonical_room_id,
  2465. "agent.updated",
  2466. switched[1],
  2467. created_at=now,
  2468. )
  2469. self._append_room_updated_summary(
  2470. connection, canonical_room_id, created_at=now
  2471. )
  2472. if interrupted["runIds"]:
  2473. self._append_agent_status(
  2474. connection, canonical_room_id, canonical_agent_id, now
  2475. )
  2476. return {
  2477. "result": result,
  2478. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  2479. }
  2480. response = self.execute_idempotent(
  2481. "agent.updated",
  2482. request_id,
  2483. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  2484. action,
  2485. )
  2486. return self._runtime_envelope(response)
  2487. def delete_agent(
  2488. self, room_id: str, agent_id: str, command: Mapping[str, object]
  2489. ) -> dict[str, object]:
  2490. return self.delete_agent_with_runtime_targets(room_id, agent_id, command)[
  2491. "result"
  2492. ]
  2493. def delete_agent_with_runtime_targets(
  2494. self, room_id: str, agent_id: str, command: Mapping[str, object]
  2495. ) -> dict[str, object]:
  2496. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2497. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  2498. command = self._command(command, {"requestId"})
  2499. request_id = self._command_request_id(command)
  2500. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2501. self._active_room(connection, canonical_room_id)
  2502. result = self._agent_detail(
  2503. connection, canonical_room_id, canonical_agent_id
  2504. )
  2505. agent_count = connection.execute(
  2506. "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
  2507. (canonical_room_id,),
  2508. ).fetchone()[0]
  2509. if agent_count <= 1:
  2510. raise GroupConflictError("Room must retain at least one agent")
  2511. now = self._now()
  2512. switched: tuple[dict[str, object], dict[str, object]] | None = None
  2513. if result["isHost"] is True:
  2514. replacement = self._first_enabled_host_candidate(
  2515. connection,
  2516. canonical_room_id,
  2517. exclude_agent_id=canonical_agent_id,
  2518. )
  2519. if replacement is None:
  2520. raise GroupConflictError(
  2521. "Host Agent cannot be removed without an enabled replacement"
  2522. )
  2523. switched = self._switch_host(
  2524. connection,
  2525. canonical_room_id,
  2526. str(replacement["id"]),
  2527. now=now,
  2528. )
  2529. interrupted = self._interrupt_runs_for_scope(
  2530. connection,
  2531. room_id=canonical_room_id,
  2532. agent_id=canonical_agent_id,
  2533. reason="Agent removed",
  2534. now=now,
  2535. )
  2536. connection.execute(
  2537. "DELETE FROM group_agents WHERE id = ? AND room_id = ?",
  2538. (canonical_agent_id, canonical_room_id),
  2539. )
  2540. connection.execute(
  2541. "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
  2542. (now, canonical_room_id),
  2543. )
  2544. if switched is not None:
  2545. self._append_event(
  2546. connection,
  2547. canonical_room_id,
  2548. "agent.updated",
  2549. switched[1],
  2550. created_at=now,
  2551. )
  2552. self._append_event(
  2553. connection, canonical_room_id, "agent.deleted", result, created_at=now
  2554. )
  2555. self._append_room_updated_summary(
  2556. connection, canonical_room_id, created_at=now
  2557. )
  2558. return {
  2559. "result": result,
  2560. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  2561. }
  2562. response = self.execute_idempotent(
  2563. "agent.deleted",
  2564. request_id,
  2565. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  2566. action,
  2567. )
  2568. return self._runtime_envelope(response)
  2569. def interrupt_agent_with_runtime_targets(
  2570. self, room_id: str, agent_id: str, command: Mapping[str, object]
  2571. ) -> dict[str, object]:
  2572. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2573. canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
  2574. command = self._command(command, {"requestId"})
  2575. request_id = self._command_request_id(command)
  2576. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2577. self._active_room(connection, canonical_room_id)
  2578. self._owned_agent(connection, canonical_room_id, canonical_agent_id)
  2579. now = self._now()
  2580. interrupted = self._interrupt_runs_for_scope(
  2581. connection,
  2582. room_id=canonical_room_id,
  2583. agent_id=canonical_agent_id,
  2584. reason="Agent interrupted",
  2585. now=now,
  2586. include_queued=False,
  2587. )
  2588. if interrupted["runIds"]:
  2589. self._append_agent_status(
  2590. connection, canonical_room_id, canonical_agent_id, now
  2591. )
  2592. return {
  2593. "result": {
  2594. "roomId": canonical_room_id,
  2595. "agentId": canonical_agent_id,
  2596. "interruptedRunIds": interrupted["runIds"],
  2597. },
  2598. "runtimeSessionIds": interrupted["runtimeSessionIds"],
  2599. }
  2600. response = self.execute_idempotent(
  2601. "agent.interrupted",
  2602. request_id,
  2603. self._scoped_payload(command, canonical_room_id, canonical_agent_id),
  2604. action,
  2605. )
  2606. return self._runtime_envelope(response)
  2607. def create_human_message(
  2608. self,
  2609. room_id: str,
  2610. *,
  2611. request_id: str,
  2612. client_message_id: str,
  2613. content: str,
  2614. mention_agent_ids: object,
  2615. topic_id: str | None = None,
  2616. ) -> dict[str, object]:
  2617. """Persist one human turn and the deterministic agent work it starts."""
  2618. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2619. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  2620. canonical_client_id = self._canonical_uuid(client_message_id, "clientMessageId")
  2621. canonical_topic_id = (
  2622. self._compatibility_topic_id(canonical_room_id)
  2623. if topic_id is None
  2624. else self._canonical_uuid(topic_id, "topicId")
  2625. )
  2626. message_content = self._message_text(
  2627. content, "content", max_bytes=MAX_MESSAGE_BYTES, nonblank=True
  2628. )
  2629. agent_ids = self._mention_agent_ids(mention_agent_ids)
  2630. payload = {
  2631. "roomId": canonical_room_id,
  2632. "clientMessageId": canonical_client_id,
  2633. "content": message_content,
  2634. "mentionAgentIds": agent_ids,
  2635. }
  2636. if topic_id is not None:
  2637. payload["topicId"] = canonical_topic_id
  2638. def action(connection: sqlite3.Connection) -> dict[str, object]:
  2639. room = self._active_room(connection, canonical_room_id)
  2640. agents: list[tuple[sqlite3.Row, str, bool]] = []
  2641. room_agents = connection.execute(
  2642. """SELECT * FROM group_agents WHERE room_id = ?
  2643. ORDER BY created_at ASC, id ASC""",
  2644. (canonical_room_id,),
  2645. ).fetchall()
  2646. parsed_ids, _warnings = self._plan_cascade_mentions(
  2647. message_content,
  2648. room_agents,
  2649. source_agent_id="human",
  2650. include_automatic=False,
  2651. )
  2652. agents_by_id = {str(agent["id"]): agent for agent in room_agents}
  2653. explicit_agent_ids = [
  2654. agent_id
  2655. for agent_id in dict.fromkeys([*agent_ids, *parsed_ids])
  2656. if agent_id in agents_by_id and agents_by_id[agent_id]["enabled"]
  2657. ]
  2658. if room["orchestration_mode"] == "host":
  2659. host = self._room_host(connection, canonical_room_id)
  2660. agents.append((host, "automatic", True))
  2661. elif explicit_agent_ids:
  2662. agents.extend(
  2663. (agents_by_id[agent_id], "mentioned", False)
  2664. for agent_id in explicit_agent_ids
  2665. )
  2666. else:
  2667. host = self._room_host(connection, canonical_room_id)
  2668. scheduled_ids: set[str] = set()
  2669. if host["enabled"]:
  2670. agents.append((host, "automatic", True))
  2671. scheduled_ids.add(str(host["id"]))
  2672. agents.extend(
  2673. (agent, "automatic", False)
  2674. for agent in room_agents
  2675. if agent["enabled"]
  2676. and agent["reply_without_mention"]
  2677. and agent["id"] not in scheduled_ids
  2678. )
  2679. now = self._now()
  2680. self._ensure_topic(
  2681. connection,
  2682. canonical_room_id,
  2683. canonical_topic_id,
  2684. message_content,
  2685. now,
  2686. )
  2687. human_id = str(uuid.uuid4())
  2688. connection.execute(
  2689. """INSERT INTO group_messages
  2690. (id, room_id, topic_id, sender_kind, sender_id, sender_name, root_message_id,
  2691. reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
  2692. status, error, created_at, updated_at)
  2693. VALUES (?, ?, ?, 'human', 'human', '你', ?, NULL, ?, ?, '', '[]', 'completed', '', ?, ?)""",
  2694. (
  2695. human_id,
  2696. canonical_room_id,
  2697. canonical_topic_id,
  2698. human_id,
  2699. canonical_client_id,
  2700. message_content,
  2701. now,
  2702. now,
  2703. ),
  2704. )
  2705. message = self._message_wire(self._message_row(connection, human_id))
  2706. self._append_event(
  2707. connection, canonical_room_id, "message.upsert", message, created_at=now
  2708. )
  2709. runs: list[dict[str, object]] = []
  2710. for agent, reply_mode, required_reply in agents:
  2711. visible = reply_mode == "mentioned" or required_reply
  2712. response_id, run_id = str(uuid.uuid4()), str(uuid.uuid4())
  2713. connection.execute(
  2714. """INSERT INTO group_messages
  2715. (id, room_id, topic_id, sender_kind, sender_id, sender_name, root_message_id,
  2716. reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
  2717. status, error, visible, created_at, updated_at)
  2718. VALUES (?, ?, ?, 'agent', ?, ?, ?, ?, NULL, '', '', '[]', 'queued', '', ?, ?, ?)""",
  2719. (
  2720. response_id,
  2721. canonical_room_id,
  2722. canonical_topic_id,
  2723. agent["id"],
  2724. agent["display_name"],
  2725. human_id,
  2726. human_id,
  2727. int(visible),
  2728. now,
  2729. now,
  2730. ),
  2731. )
  2732. connection.execute(
  2733. """INSERT INTO group_agent_runs
  2734. (id, room_id, topic_id, agent_id, trigger_message_id, response_message_id, root_message_id,
  2735. depth, reply_mode, required_reply, status, runtime_session_id,
  2736. requested_model, requested_provider,
  2737. requested_reasoning_effort, requested_fast_mode,
  2738. actual_model, actual_provider, actual_reasoning_effort,
  2739. actual_fast_mode, error, created_at, updated_at)
  2740. VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 'queued', NULL,
  2741. ?, ?, ?, ?, NULL, NULL, NULL, NULL, '', ?, ?)""",
  2742. (
  2743. run_id,
  2744. canonical_room_id,
  2745. canonical_topic_id,
  2746. agent["id"],
  2747. human_id,
  2748. response_id,
  2749. human_id,
  2750. reply_mode,
  2751. int(required_reply),
  2752. agent["model_override"],
  2753. agent["provider_override"],
  2754. agent["reasoning_effort_override"],
  2755. agent["fast_mode_override"],
  2756. now,
  2757. now,
  2758. ),
  2759. )
  2760. response = self._message_wire(
  2761. self._message_row(connection, response_id)
  2762. )
  2763. run = self._run_wire(self._run_row(connection, run_id))
  2764. if visible:
  2765. self._append_event(
  2766. connection,
  2767. canonical_room_id,
  2768. "message.upsert",
  2769. response,
  2770. created_at=now,
  2771. )
  2772. self._append_event(
  2773. connection, canonical_room_id, "run.updated", run, created_at=now
  2774. )
  2775. runs.append(run)
  2776. return {"message": message, "runs": runs}
  2777. try:
  2778. return self.execute_idempotent(
  2779. "message.create", canonical_request_id, payload, action
  2780. )
  2781. except sqlite3.IntegrityError as error:
  2782. raise self._integrity_conflict(error) from error
  2783. def get_message(self, message_id: str) -> dict[str, object]:
  2784. canonical_message_id = self._canonical_uuid(message_id, "messageId")
  2785. with self.read_transaction() as connection:
  2786. return self._message_wire(
  2787. self._message_with_execution_row(connection, canonical_message_id)
  2788. )
  2789. def get_run(self, run_id: str) -> dict[str, object]:
  2790. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2791. with self.read_transaction() as connection:
  2792. return self._run_wire(self._run_row(connection, canonical_run_id))
  2793. def get_interaction(self, interaction_id: str) -> dict[str, object]:
  2794. canonical_interaction_id = self._interaction_id(interaction_id)
  2795. with self.read_transaction() as connection:
  2796. return self._interaction_wire(
  2797. self._interaction_row(connection, canonical_interaction_id)
  2798. )
  2799. def list_messages(
  2800. self,
  2801. room_id: str,
  2802. *,
  2803. topic_id: str | None = None,
  2804. before_seq: int | None = None,
  2805. after_seq: int | None = None,
  2806. limit: int = MAX_MESSAGE_PAGE_SIZE,
  2807. ) -> list[dict[str, object]]:
  2808. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  2809. canonical_topic_id = (
  2810. None
  2811. if topic_id is None
  2812. else self._canonical_uuid(topic_id, "topicId")
  2813. )
  2814. self._page_limit(limit, MAX_MESSAGE_PAGE_SIZE, "limit")
  2815. if before_seq is not None and after_seq is not None:
  2816. raise ValueError("before_seq and after_seq are mutually exclusive")
  2817. before = (
  2818. self._positive_int(before_seq, "before_seq")
  2819. if before_seq is not None
  2820. else None
  2821. )
  2822. after = (
  2823. self._positive_int(after_seq, "after_seq")
  2824. if after_seq is not None
  2825. else None
  2826. )
  2827. with self.read_transaction() as connection:
  2828. self._room_detail(connection, canonical_room_id, include_archived=True)
  2829. if canonical_topic_id is not None:
  2830. self._topic_row(connection, canonical_room_id, canonical_topic_id)
  2831. scope = "message.room_id = ?"
  2832. scope_params: tuple[object, ...] = (canonical_room_id,)
  2833. if canonical_topic_id is not None:
  2834. scope += " AND message.topic_id = ?"
  2835. scope_params = (canonical_room_id, canonical_topic_id)
  2836. select = """SELECT message.*,
  2837. run.requested_model AS execution_requested_model,
  2838. run.requested_provider AS execution_requested_provider,
  2839. run.requested_reasoning_effort AS execution_requested_reasoning_effort,
  2840. run.requested_fast_mode AS execution_requested_fast_mode,
  2841. run.actual_model AS execution_actual_model,
  2842. run.actual_provider AS execution_actual_provider,
  2843. run.actual_reasoning_effort AS execution_actual_reasoning_effort,
  2844. run.actual_fast_mode AS execution_actual_fast_mode
  2845. FROM group_messages AS message
  2846. LEFT JOIN group_agent_runs AS run
  2847. ON run.response_message_id = message.id"""
  2848. if before is not None:
  2849. rows = connection.execute(
  2850. f"{select} WHERE {scope} AND message.visible = 1 AND message.seq < ? ORDER BY message.seq DESC LIMIT ?",
  2851. (*scope_params, before, limit),
  2852. ).fetchall()
  2853. rows = list(reversed(rows))
  2854. elif after is not None:
  2855. rows = connection.execute(
  2856. f"{select} WHERE {scope} AND message.visible = 1 AND message.seq > ? ORDER BY message.seq ASC LIMIT ?",
  2857. (*scope_params, after, limit),
  2858. ).fetchall()
  2859. else:
  2860. rows = connection.execute(
  2861. f"{select} WHERE {scope} AND message.visible = 1 ORDER BY message.seq DESC LIMIT ?",
  2862. (*scope_params, limit),
  2863. ).fetchall()
  2864. rows = list(reversed(rows))
  2865. return [self._message_wire(row) for row in rows]
  2866. def claim_next_runnable_run(self) -> dict[str, object] | None:
  2867. """Atomically claim the oldest eligible queued run."""
  2868. with self.write_transaction() as connection:
  2869. active_count = int(
  2870. connection.execute(
  2871. """SELECT COUNT(*) FROM group_agent_runs
  2872. WHERE status IN ('running', 'awaiting_input')"""
  2873. ).fetchone()[0]
  2874. )
  2875. if active_count >= MAX_PLUGIN_CONCURRENCY:
  2876. return None
  2877. run = connection.execute(
  2878. """SELECT candidate.* FROM group_agent_runs AS candidate
  2879. JOIN group_rooms AS room ON room.id = candidate.room_id
  2880. JOIN group_agents AS agent
  2881. ON agent.id = candidate.agent_id
  2882. AND agent.room_id = candidate.room_id
  2883. JOIN group_messages AS trigger_message
  2884. ON trigger_message.id = candidate.trigger_message_id
  2885. JOIN group_messages AS root_message
  2886. ON root_message.id = candidate.root_message_id
  2887. WHERE candidate.status = 'queued'
  2888. AND room.archived = 0
  2889. AND agent.enabled = 1
  2890. AND NOT EXISTS (
  2891. SELECT 1 FROM group_agent_runs AS occupied_agent
  2892. WHERE occupied_agent.agent_id = candidate.agent_id
  2893. AND occupied_agent.status IN ('running', 'awaiting_input')
  2894. )
  2895. AND (
  2896. SELECT COUNT(*) FROM group_agent_runs AS occupied_room
  2897. WHERE occupied_room.room_id = candidate.room_id
  2898. AND occupied_room.status IN ('running', 'awaiting_input')
  2899. ) < ?
  2900. AND (
  2901. room.orchestration_mode != 'host'
  2902. OR NOT EXISTS (
  2903. SELECT 1 FROM group_agent_runs AS occupied_topic
  2904. WHERE occupied_topic.topic_id = candidate.topic_id
  2905. AND occupied_topic.status IN ('running', 'awaiting_input')
  2906. )
  2907. OR (
  2908. agent.is_host = 0
  2909. AND NOT EXISTS (
  2910. SELECT 1 FROM group_agent_runs AS occupied_topic
  2911. JOIN group_agents AS occupied_topic_agent
  2912. ON occupied_topic_agent.id = occupied_topic.agent_id
  2913. WHERE occupied_topic.topic_id = candidate.topic_id
  2914. AND occupied_topic.status IN ('running', 'awaiting_input')
  2915. AND (
  2916. occupied_topic.root_message_id != candidate.root_message_id
  2917. OR occupied_topic.trigger_message_id != candidate.trigger_message_id
  2918. OR occupied_topic.depth != candidate.depth
  2919. OR occupied_topic_agent.is_host = 1
  2920. )
  2921. )
  2922. )
  2923. )
  2924. ORDER BY CASE WHEN room.orchestration_mode = 'host'
  2925. THEN root_message.seq ELSE trigger_message.seq END ASC,
  2926. trigger_message.seq ASC,
  2927. candidate.created_at ASC,
  2928. candidate.id ASC
  2929. LIMIT 1""",
  2930. (MAX_ROOM_CONCURRENCY,),
  2931. ).fetchone()
  2932. if run is None:
  2933. return None
  2934. response = self._message_row(connection, run["response_message_id"])
  2935. self._validate_run_message_state(run, response)
  2936. now = self._now()
  2937. result = self._update_run(connection, run, "running", now, UNSET, UNSET)
  2938. self._append_event(
  2939. connection,
  2940. run["room_id"],
  2941. "run.updated",
  2942. result,
  2943. created_at=now,
  2944. )
  2945. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  2946. return result
  2947. def read_run_projection(self, run_id: str) -> dict[str, object]:
  2948. """Return a stable, bounded context projection for one claimed run."""
  2949. canonical_run_id = self._canonical_uuid(run_id, "runId")
  2950. with self.read_transaction() as connection:
  2951. run = self._run_row(connection, canonical_run_id)
  2952. if run["status"] not in {"running", "awaiting_input"}:
  2953. raise GroupConflictError("Run is not claimed")
  2954. room = self._active_room(connection, run["room_id"])
  2955. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  2956. trigger = self._message_row(connection, run["trigger_message_id"])
  2957. if (
  2958. trigger["room_id"] != run["room_id"]
  2959. or trigger["topic_id"] != run["topic_id"]
  2960. ):
  2961. raise GroupStoreError("Run trigger message is corrupt")
  2962. topic_state = self._agent_topic_state(
  2963. connection, run["agent_id"], run["topic_id"]
  2964. )
  2965. lower_seq = int(topic_state["last_context_message_seq"])
  2966. trigger_seq = int(trigger["seq"])
  2967. through_seq = self._safe_context_seq(
  2968. connection,
  2969. run["room_id"],
  2970. run["topic_id"],
  2971. lower_seq,
  2972. trigger_seq,
  2973. )
  2974. eligibility = """FROM group_messages
  2975. WHERE room_id = ? AND topic_id = ? AND seq > ? AND seq <= ?
  2976. AND visible = 1
  2977. AND status IN ('completed', 'failed', 'interrupted')
  2978. AND NOT (sender_kind = 'agent' AND sender_id = ?)"""
  2979. parameters = (
  2980. run["room_id"],
  2981. run["topic_id"],
  2982. lower_seq,
  2983. trigger_seq,
  2984. run["agent_id"],
  2985. )
  2986. total = int(
  2987. connection.execute(
  2988. f"SELECT COUNT(*) {eligibility}", parameters
  2989. ).fetchone()[0]
  2990. )
  2991. rows = connection.execute(
  2992. f"""SELECT * {eligibility}
  2993. ORDER BY seq DESC LIMIT ?""",
  2994. (*parameters, INITIAL_CONTEXT_MESSAGE_LIMIT),
  2995. ).fetchall()
  2996. rows = list(reversed(rows))
  2997. omitted = total - len(rows)
  2998. omitted_through_seq: int | None = None
  2999. if omitted:
  3000. omitted_through_seq = int(
  3001. connection.execute(
  3002. f"""SELECT MAX(seq) {eligibility}
  3003. AND seq < ?""",
  3004. (*parameters, rows[0]["seq"]),
  3005. ).fetchone()[0]
  3006. )
  3007. initial = agent["stored_session_id"] is None
  3008. projected_agent = self._agent_wire(agent)
  3009. projected_agent["lastContextMessageSeq"] = lower_seq
  3010. messages = [self._projection_message(row) for row in rows]
  3011. messages, omitted, omitted_through_seq, omitted_summary = (
  3012. self._bound_projection_messages(
  3013. messages,
  3014. omitted_count=omitted,
  3015. omitted_through_seq=omitted_through_seq,
  3016. )
  3017. )
  3018. projected_run = self._run_wire(run)
  3019. projected_run["requiredReply"] = bool(run["required_reply"])
  3020. return {
  3021. "run": projected_run,
  3022. "room": self._room_wire(room),
  3023. "agent": projected_agent,
  3024. "messages": messages,
  3025. "initial": initial,
  3026. "triggerSeq": trigger_seq,
  3027. "throughSeq": through_seq,
  3028. "omittedMessageCount": omitted,
  3029. "omittedThroughSeq": omitted_through_seq,
  3030. "omittedSummary": omitted_summary,
  3031. "characterBudget": CONTEXT_CHARACTER_BUDGET,
  3032. }
  3033. def bind_run_session(
  3034. self,
  3035. run_id: str,
  3036. *,
  3037. expected_stored_session_id: str | None,
  3038. stored_session_id: str,
  3039. runtime_session_id: str,
  3040. ) -> dict[str, object]:
  3041. """CAS-bind stored and runtime identities for the current generation."""
  3042. canonical_run_id = self._canonical_uuid(run_id, "runId")
  3043. expected_stored = self._runtime_session_id(expected_stored_session_id)
  3044. stored = self._runtime_session_id(stored_session_id)
  3045. runtime = self._runtime_session_id(runtime_session_id)
  3046. if stored is None:
  3047. raise ValueError("storedSessionId is invalid")
  3048. if runtime is None:
  3049. raise ValueError("runtimeSessionId is invalid")
  3050. with self.write_transaction() as connection:
  3051. run = self._run_row(connection, canonical_run_id)
  3052. self._active_room(connection, run["room_id"])
  3053. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3054. response = self._message_row(connection, run["response_message_id"])
  3055. self._validate_run_message_state(run, response)
  3056. if run["status"] not in {"running", "awaiting_input"}:
  3057. raise GroupConflictError("Run does not accept a session binding")
  3058. if agent["stored_session_id"] != expected_stored:
  3059. raise GroupConflictError("stored session generation changed")
  3060. if run["runtime_session_id"] not in {None, runtime}:
  3061. raise GroupConflictError("Run runtime is already bound")
  3062. self._require_available_runtime(connection, runtime, canonical_run_id)
  3063. now = self._now()
  3064. if agent["stored_session_id"] != stored:
  3065. connection.execute(
  3066. """UPDATE group_agents
  3067. SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
  3068. (stored, now, agent["id"]),
  3069. )
  3070. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  3071. self._append_event(
  3072. connection,
  3073. run["room_id"],
  3074. "agent.updated",
  3075. self._agent_wire(agent),
  3076. created_at=now,
  3077. )
  3078. if run["runtime_session_id"] != runtime:
  3079. changed = self._update_run(
  3080. connection, run, run["status"], now, runtime, UNSET
  3081. )
  3082. self._append_event(
  3083. connection,
  3084. run["room_id"],
  3085. "run.updated",
  3086. changed,
  3087. created_at=now,
  3088. )
  3089. else:
  3090. changed = self._run_wire(run)
  3091. return {"run": changed, "agent": self._agent_wire(agent)}
  3092. def advance_run_context(
  3093. self,
  3094. run_id: str,
  3095. *,
  3096. runtime_session_id: str,
  3097. expected_context_seq: int,
  3098. through_seq: int,
  3099. ) -> dict[str, object]:
  3100. """Advance one Agent context watermark with generation and hole CAS checks."""
  3101. canonical_run_id = self._canonical_uuid(run_id, "runId")
  3102. runtime = self._runtime_session_id(runtime_session_id)
  3103. if runtime is None:
  3104. raise ValueError("runtimeSessionId is invalid")
  3105. expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
  3106. through = self._nonnegative_int(through_seq, "throughSeq")
  3107. with self.write_transaction() as connection:
  3108. run = self._run_row(connection, canonical_run_id)
  3109. self._active_room(connection, run["room_id"])
  3110. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3111. if run["status"] not in {"running", "awaiting_input"}:
  3112. raise GroupConflictError("Run no longer accepts context")
  3113. if run["runtime_session_id"] != runtime:
  3114. raise GroupConflictError("Run runtime generation changed")
  3115. topic_state = self._agent_topic_state(
  3116. connection, run["agent_id"], run["topic_id"]
  3117. )
  3118. if int(topic_state["last_context_message_seq"]) != expected:
  3119. raise GroupConflictError("Agent context generation changed")
  3120. trigger = self._message_row(connection, run["trigger_message_id"])
  3121. safe = self._safe_context_seq(
  3122. connection,
  3123. run["room_id"],
  3124. run["topic_id"],
  3125. expected,
  3126. int(trigger["seq"]),
  3127. )
  3128. if through < expected or through > safe:
  3129. raise GroupConflictError("throughSeq exceeds safe projection")
  3130. now = self._now()
  3131. connection.execute(
  3132. """UPDATE group_agent_topic_state
  3133. SET last_context_message_seq = ?, updated_at = ?
  3134. WHERE agent_id = ? AND topic_id = ?""",
  3135. (through, now, agent["id"], run["topic_id"]),
  3136. )
  3137. changed = self._agent_wire(agent)
  3138. changed["lastContextMessageSeq"] = through
  3139. return changed
  3140. def commit_prompt_submission(
  3141. self,
  3142. run_id: str,
  3143. *,
  3144. expected_stored_session_id: str | None,
  3145. stored_session_id: str,
  3146. runtime_session_id: str,
  3147. expected_context_seq: int,
  3148. through_seq: int,
  3149. ) -> dict[str, object]:
  3150. """Commit a successful prompt submission and its durable context CAS."""
  3151. canonical_run_id = self._canonical_uuid(run_id, "runId")
  3152. expected_stored = self._runtime_session_id(expected_stored_session_id)
  3153. stored = self._runtime_session_id(stored_session_id)
  3154. runtime = self._runtime_session_id(runtime_session_id)
  3155. expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
  3156. through = self._nonnegative_int(through_seq, "throughSeq")
  3157. if stored is None:
  3158. raise ValueError("storedSessionId is invalid")
  3159. if runtime is None:
  3160. raise ValueError("runtimeSessionId is invalid")
  3161. operation = f"run.prompt.submitted:{canonical_run_id}"
  3162. legacy_ledger_id = str(
  3163. uuid.uuid5(
  3164. uuid.NAMESPACE_URL,
  3165. f"hermes://yaoyao-group/{canonical_run_id}/prompt-submission",
  3166. )
  3167. )
  3168. ledger_id = f"internal:prompt:{canonical_run_id}"
  3169. payload = {
  3170. "runId": canonical_run_id,
  3171. "expectedStoredSessionId": expected_stored,
  3172. "storedSessionId": stored,
  3173. "runtimeSessionId": runtime,
  3174. "expectedContextSeq": expected,
  3175. "throughSeq": through,
  3176. }
  3177. request_hash = hashlib.sha256(
  3178. self._canonical_json(payload).encode()
  3179. ).hexdigest()
  3180. with self.write_transaction() as connection:
  3181. run = self._run_row(connection, canonical_run_id)
  3182. self._active_room(connection, run["room_id"])
  3183. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3184. response = self._message_row(connection, run["response_message_id"])
  3185. self._validate_run_message_state(run, response)
  3186. if run["status"] != "running":
  3187. raise GroupConflictError("Run no longer accepts a prompt submission")
  3188. if run["runtime_session_id"] != runtime:
  3189. raise GroupConflictError("Run runtime generation changed")
  3190. current_stored = agent["stored_session_id"]
  3191. topic_state = self._agent_topic_state(
  3192. connection, run["agent_id"], run["topic_id"]
  3193. )
  3194. current_context = int(topic_state["last_context_message_seq"])
  3195. existing = connection.execute(
  3196. """SELECT request_id, operation, request_hash, response_json
  3197. FROM group_idempotency WHERE request_id = ?""",
  3198. (ledger_id,),
  3199. ).fetchone()
  3200. legacy_existing = None
  3201. if existing is None:
  3202. candidate = connection.execute(
  3203. """SELECT operation, request_hash, response_json
  3204. FROM group_idempotency WHERE request_id = ?""",
  3205. (legacy_ledger_id,),
  3206. ).fetchone()
  3207. if candidate is not None and candidate["operation"] == operation:
  3208. existing = candidate
  3209. legacy_existing = candidate
  3210. if existing is not None:
  3211. if (
  3212. existing["operation"] != operation
  3213. or existing["request_hash"] != request_hash
  3214. ):
  3215. raise GroupConflictError("Prompt submission generation changed")
  3216. if current_stored != stored or current_context != through:
  3217. raise GroupConflictError("Prompt submission generation changed")
  3218. stored_response = existing["response_json"]
  3219. try:
  3220. replay = self._load_json(stored_response)
  3221. except (TypeError, ValueError, json.JSONDecodeError) as error:
  3222. raise GroupStoreError(
  3223. "Stored prompt submission is corrupt"
  3224. ) from error
  3225. if (
  3226. not isinstance(replay, dict)
  3227. or self._canonical_json(replay) != stored_response
  3228. ):
  3229. raise GroupStoreError("Stored prompt submission is corrupt")
  3230. if legacy_existing is not None:
  3231. connection.execute(
  3232. """UPDATE group_idempotency SET request_id = ?
  3233. WHERE request_id = ?""",
  3234. (ledger_id, legacy_ledger_id),
  3235. )
  3236. return replay
  3237. if current_stored != expected_stored:
  3238. raise GroupConflictError("stored session generation changed")
  3239. if current_context != expected:
  3240. raise GroupConflictError("Agent context generation changed")
  3241. trigger = self._message_row(connection, run["trigger_message_id"])
  3242. safe = self._safe_context_seq(
  3243. connection,
  3244. run["room_id"],
  3245. run["topic_id"],
  3246. expected,
  3247. int(trigger["seq"]),
  3248. )
  3249. if through < expected or through > safe:
  3250. raise GroupConflictError("throughSeq exceeds safe projection")
  3251. now = self._now()
  3252. if current_stored != stored:
  3253. connection.execute(
  3254. """UPDATE group_agents
  3255. SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
  3256. (stored, now, agent["id"]),
  3257. )
  3258. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  3259. self._append_event(
  3260. connection,
  3261. run["room_id"],
  3262. "agent.updated",
  3263. self._agent_wire(agent),
  3264. created_at=now,
  3265. )
  3266. if current_context != through:
  3267. connection.execute(
  3268. """UPDATE group_agent_topic_state
  3269. SET last_context_message_seq = ?, updated_at = ?
  3270. WHERE agent_id = ? AND topic_id = ?""",
  3271. (through, now, agent["id"], run["topic_id"]),
  3272. )
  3273. result_agent = self._agent_wire(agent)
  3274. result_agent["lastContextMessageSeq"] = through
  3275. result = {
  3276. "run": self._run_wire(run),
  3277. "agent": result_agent,
  3278. }
  3279. connection.execute(
  3280. """INSERT INTO group_idempotency
  3281. (request_id, operation, request_hash, response_json, created_at)
  3282. VALUES (?, ?, ?, ?, ?)""",
  3283. (
  3284. ledger_id,
  3285. operation,
  3286. request_hash,
  3287. self._canonical_json(result),
  3288. now,
  3289. ),
  3290. )
  3291. return result
  3292. def settle_run(
  3293. self,
  3294. run_id: str,
  3295. *,
  3296. runtime_session_id: str | None,
  3297. expected_stored_session_id: str | None,
  3298. stored_session_id: str | None,
  3299. outcome: str,
  3300. actual_model: str | None = None,
  3301. actual_provider: str | None = None,
  3302. actual_reasoning_effort: str | None = None,
  3303. actual_fast_mode: bool | None = None,
  3304. error: str = "",
  3305. ) -> dict[str, object]:
  3306. """Settle message, run, session rotation, and status in one transaction."""
  3307. canonical_run_id = self._canonical_uuid(run_id, "runId")
  3308. runtime = self._runtime_session_id(runtime_session_id)
  3309. expected_stored = self._runtime_session_id(expected_stored_session_id)
  3310. stored = self._runtime_session_id(stored_session_id)
  3311. effective_model = self._agent_configuration_value(actual_model, "model")
  3312. effective_provider = self._agent_configuration_value(
  3313. actual_provider, "provider"
  3314. )
  3315. if (effective_model is None) != (effective_provider is None):
  3316. raise ValueError("actual model and provider must both be set or both be null")
  3317. effective_reasoning = self._agent_configuration_value(
  3318. actual_reasoning_effort, "reasoningEffort"
  3319. )
  3320. if actual_fast_mode is not None and not isinstance(actual_fast_mode, bool):
  3321. raise ValueError("actual fast mode must be a boolean or null")
  3322. run_error = self._message_text(error, "error", max_bytes=4096)
  3323. if outcome not in {"completed", "failed", "interrupted"}:
  3324. raise ValueError("outcome is invalid")
  3325. if runtime is None and outcome != "failed":
  3326. raise ValueError("A runtime-less settle only supports failed")
  3327. with self.write_transaction() as connection:
  3328. run = self._run_row(connection, canonical_run_id)
  3329. room = self._active_room(connection, run["room_id"])
  3330. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  3331. response = self._message_row(connection, run["response_message_id"])
  3332. self._validate_run_message_state(run, response)
  3333. if run["status"] not in {"running", "awaiting_input"}:
  3334. raise GroupConflictError("Run is already settled")
  3335. if run["runtime_session_id"] != runtime:
  3336. raise GroupConflictError("Run runtime generation changed")
  3337. if agent["stored_session_id"] != expected_stored:
  3338. raise GroupConflictError("stored session generation changed")
  3339. if outcome == "completed" and response["status"] != "completed":
  3340. raise GroupConflictError("Response message must be completed first")
  3341. now = self._now()
  3342. if stored != agent["stored_session_id"]:
  3343. connection.execute(
  3344. """UPDATE group_agents
  3345. SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
  3346. (stored, now, agent["id"]),
  3347. )
  3348. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  3349. self._append_event(
  3350. connection,
  3351. run["room_id"],
  3352. "agent.updated",
  3353. self._agent_wire(agent),
  3354. created_at=now,
  3355. )
  3356. connection.execute(
  3357. """UPDATE group_agent_runs
  3358. SET actual_model = ?, actual_provider = ?,
  3359. actual_reasoning_effort = ?, actual_fast_mode = ?
  3360. WHERE id = ?""",
  3361. (
  3362. effective_model,
  3363. effective_provider,
  3364. effective_reasoning,
  3365. None if actual_fast_mode is None else int(actual_fast_mode),
  3366. run["id"],
  3367. ),
  3368. )
  3369. run = self._run_row(connection, run["id"])
  3370. self._cancel_pending_interactions(connection, run, now)
  3371. changed = self._update_run(connection, run, outcome, now, None, run_error)
  3372. self._fail_claimed_interaction_ledgers(
  3373. connection,
  3374. run_id=run["id"],
  3375. reason=run_error or f"Run {outcome}",
  3376. runtime_session_ids=[] if runtime is None else [runtime],
  3377. run=changed,
  3378. )
  3379. self._append_event(
  3380. connection,
  3381. run["room_id"],
  3382. "run.updated",
  3383. changed,
  3384. created_at=now,
  3385. )
  3386. if (
  3387. outcome in {"failed", "interrupted"}
  3388. and response["status"] != "completed"
  3389. ):
  3390. connection.execute(
  3391. """UPDATE group_messages
  3392. SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
  3393. (outcome, run_error, now, response["id"]),
  3394. )
  3395. response = self._message_row(connection, response["id"])
  3396. if response["visible"]:
  3397. self._append_event(
  3398. connection,
  3399. run["room_id"],
  3400. "message.upsert",
  3401. self._message_wire(
  3402. self._message_with_execution_row(
  3403. connection, response["id"]
  3404. )
  3405. ),
  3406. created_at=now,
  3407. )
  3408. elif (
  3409. effective_model is not None
  3410. or effective_reasoning is not None
  3411. or actual_fast_mode is not None
  3412. ) and response["visible"]:
  3413. self._append_event(
  3414. connection,
  3415. run["room_id"],
  3416. "message.upsert",
  3417. self._message_wire(
  3418. self._message_with_execution_row(connection, response["id"])
  3419. ),
  3420. created_at=now,
  3421. )
  3422. if outcome == "completed" or (
  3423. room["orchestration_mode"] == "host" and not agent["is_host"]
  3424. ):
  3425. self._record_cascade_plan(
  3426. connection,
  3427. source=run,
  3428. source_message=response,
  3429. created_at=now,
  3430. )
  3431. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  3432. return {
  3433. "run": changed,
  3434. "message": self._message_wire(
  3435. self._message_with_execution_row(connection, response["id"])
  3436. ),
  3437. "agent": self._agent_wire(agent),
  3438. }
  3439. @classmethod
  3440. def _cascade_request_id(cls, source_run_id: str) -> str:
  3441. return f"internal:cascade:{source_run_id}"
  3442. @classmethod
  3443. def _cascade_request_hash(
  3444. cls, source_run_id: str, *, parse_version: int = _CASCADE_PARSE_VERSION
  3445. ) -> str:
  3446. payload = {
  3447. "parseVersion": parse_version,
  3448. "sourceRunId": source_run_id,
  3449. "version": 1,
  3450. }
  3451. return hashlib.sha256(cls._canonical_json(payload).encode()).hexdigest()
  3452. def _record_cascade_plan(
  3453. self,
  3454. connection: sqlite3.Connection,
  3455. *,
  3456. source: sqlite3.Row,
  3457. source_message: sqlite3.Row,
  3458. created_at: float,
  3459. ) -> None:
  3460. request_id = self._cascade_request_id(source["id"])
  3461. existing = connection.execute(
  3462. "SELECT 1 FROM group_idempotency WHERE request_id = ?",
  3463. (request_id,),
  3464. ).fetchone()
  3465. if existing is not None:
  3466. raise GroupStoreError("Cascade ledger already exists")
  3467. agents = connection.execute(
  3468. "SELECT * FROM group_agents WHERE room_id = ? "
  3469. "ORDER BY created_at ASC, id ASC",
  3470. (source["room_id"],),
  3471. ).fetchall()
  3472. room = self._active_room(connection, source["room_id"])
  3473. source_agent = next(
  3474. (agent for agent in agents if agent["id"] == source["agent_id"]), None
  3475. )
  3476. if source_agent is None:
  3477. raise GroupStoreError("Cascade source Agent is missing")
  3478. if room["orchestration_mode"] == "host":
  3479. if source_agent["is_host"] and source_message["visible"]:
  3480. target_ids, warnings = self._plan_cascade_mentions(
  3481. source_message["content"],
  3482. agents,
  3483. source_agent_id=source["agent_id"],
  3484. include_automatic=False,
  3485. )
  3486. explicit_ids = list(target_ids)
  3487. elif not source_agent["is_host"]:
  3488. host = next(
  3489. (agent for agent in agents if agent["is_host"] and agent["enabled"]),
  3490. None,
  3491. )
  3492. if host is None:
  3493. raise GroupStoreError("Host flow has no enabled host Agent")
  3494. target_ids, warnings = [str(host["id"])], []
  3495. explicit_ids = []
  3496. else:
  3497. target_ids, warnings = [], []
  3498. explicit_ids = []
  3499. elif source_message["visible"]:
  3500. target_ids, warnings = self._plan_cascade_mentions(
  3501. source_message["content"],
  3502. agents,
  3503. source_agent_id=source["agent_id"],
  3504. )
  3505. explicit_ids, _ = self._plan_cascade_mentions(
  3506. source_message["content"],
  3507. agents,
  3508. source_agent_id=source["agent_id"],
  3509. include_automatic=False,
  3510. )
  3511. else:
  3512. target_ids, warnings = [], []
  3513. explicit_ids = []
  3514. explicit_set = set(explicit_ids)
  3515. plan = {
  3516. "parseVersion": _CASCADE_PARSE_VERSION,
  3517. "sourceMessageId": source_message["id"],
  3518. "sourceRunId": source["id"],
  3519. "state": "pending",
  3520. "targets": [
  3521. {
  3522. "agentId": agent_id,
  3523. "replyMode": (
  3524. "mentioned" if agent_id in explicit_set else "automatic"
  3525. ),
  3526. }
  3527. for agent_id in target_ids
  3528. ],
  3529. "warnings": warnings,
  3530. "version": 1,
  3531. }
  3532. encoded = self._canonical_json(plan)
  3533. if len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES:
  3534. raise GroupStoreError("Cascade plan exceeds the internal limit")
  3535. connection.execute(
  3536. """INSERT INTO group_idempotency
  3537. (request_id, operation, request_hash, response_json, created_at)
  3538. VALUES (?, ?, ?, ?, ?)""",
  3539. (
  3540. request_id,
  3541. _CASCADE_PENDING_OPERATION,
  3542. self._cascade_request_hash(source["id"]),
  3543. encoded,
  3544. created_at,
  3545. ),
  3546. )
  3547. def _record_host_flow_terminal_plan_if_needed(
  3548. self,
  3549. connection: sqlite3.Connection,
  3550. run: sqlite3.Row,
  3551. created_at: float,
  3552. ) -> None:
  3553. room = connection.execute(
  3554. "SELECT orchestration_mode, archived FROM group_rooms WHERE id = ?",
  3555. (run["room_id"],),
  3556. ).fetchone()
  3557. agent = connection.execute(
  3558. "SELECT is_host, enabled FROM group_agents WHERE id = ? AND room_id = ?",
  3559. (run["agent_id"], run["room_id"]),
  3560. ).fetchone()
  3561. if (
  3562. room is None
  3563. or room["archived"]
  3564. or room["orchestration_mode"] != "host"
  3565. or agent is None
  3566. or not agent["enabled"]
  3567. or agent["is_host"]
  3568. ):
  3569. return
  3570. self._record_cascade_plan(
  3571. connection,
  3572. source=run,
  3573. source_message=self._message_row(connection, run["response_message_id"]),
  3574. created_at=created_at,
  3575. )
  3576. @classmethod
  3577. def _plan_cascade_mentions(
  3578. cls,
  3579. content: str,
  3580. agents: list[sqlite3.Row],
  3581. *,
  3582. source_agent_id: str,
  3583. include_automatic: bool = True,
  3584. ) -> tuple[list[str], list[dict[str, str]]]:
  3585. searchable = cls._mention_search_text(content)
  3586. entries: list[tuple[str, int, sqlite3.Row]] = []
  3587. for agent in agents:
  3588. aliases = (
  3589. (agent["id"], 0),
  3590. (agent["profile"], 1),
  3591. (agent["display_name"], 2),
  3592. )
  3593. seen: set[str] = set()
  3594. for alias, priority in aliases:
  3595. key = alias.casefold()
  3596. if key in seen or is_reserved_mention_alias(key):
  3597. continue
  3598. seen.add(key)
  3599. entries.append((key, priority, agent))
  3600. entries.sort(key=lambda item: (-len(item[0]), item[1], item[0], item[2]["id"]))
  3601. targets: list[str] = []
  3602. warning_names: list[str] = []
  3603. index = 0
  3604. while index < len(searchable):
  3605. if searchable[index] != "@" or (
  3606. index > 0 and cls._mention_word_char(searchable[index - 1])
  3607. ):
  3608. index += 1
  3609. continue
  3610. room_wide_match = next(
  3611. (
  3612. match
  3613. for alias in ALL_MENTION_ALIASES
  3614. if (match := cls._casefold_prefix(searchable, index + 1, alias))
  3615. is not None
  3616. and cls._mention_end(searchable, match)
  3617. ),
  3618. None,
  3619. )
  3620. if room_wide_match is not None:
  3621. for agent in agents:
  3622. if (
  3623. agent["enabled"]
  3624. and agent["id"] != source_agent_id
  3625. and agent["id"] not in targets
  3626. ):
  3627. targets.append(agent["id"])
  3628. index = room_wide_match
  3629. continue
  3630. matched = False
  3631. for key, _priority, agent in entries:
  3632. end = cls._casefold_prefix(searchable, index + 1, key)
  3633. if end is None or not cls._mention_end(searchable, end):
  3634. continue
  3635. matched = True
  3636. if not agent["enabled"]:
  3637. warning_names.append(f"Agent disabled: {agent['display_name']}")
  3638. elif agent["id"] != source_agent_id and agent["id"] not in targets:
  3639. targets.append(agent["id"])
  3640. index = end
  3641. break
  3642. if matched:
  3643. continue
  3644. token = re.match(
  3645. r"[^\s@,,。!?!?;;::()()\[\]{}]{1,100}",
  3646. searchable[index + 1 :],
  3647. )
  3648. if token is not None:
  3649. warning_names.append(f"Unknown Mention: @{token.group(0)}")
  3650. index += 1 + len(token.group(0))
  3651. else:
  3652. index += 1
  3653. if include_automatic and not targets:
  3654. for agent in agents:
  3655. if (
  3656. agent["enabled"]
  3657. and agent["reply_without_mention"]
  3658. and agent["id"] != source_agent_id
  3659. and agent["id"] not in targets
  3660. ):
  3661. targets.append(agent["id"])
  3662. warnings = [
  3663. {"code": "mention", "message": value}
  3664. for value in list(dict.fromkeys(warning_names))[:MAX_AGENTS_PER_ROOM]
  3665. ]
  3666. return targets[:MAX_AGENTS_PER_ROOM], warnings
  3667. @staticmethod
  3668. def _casefold_prefix(content: str, start: int, expected: str) -> int | None:
  3669. folded = ""
  3670. index = start
  3671. while index < len(content) and len(folded) < len(expected):
  3672. folded += content[index].casefold()
  3673. index += 1
  3674. return index if folded == expected else None
  3675. @staticmethod
  3676. def _mention_search_text(content: str) -> str:
  3677. lines = content.splitlines(keepends=True)
  3678. visible: list[str] = []
  3679. fence: tuple[str, int] | None = None
  3680. for line in lines:
  3681. leading_spaces = len(line) - len(line.lstrip(" "))
  3682. candidate = line[leading_spaces:] if leading_spaces <= 3 else ""
  3683. marker_character = (
  3684. candidate[0]
  3685. if candidate.startswith("`") or candidate.startswith("~")
  3686. else None
  3687. )
  3688. marker_length = 0
  3689. if marker_character is not None:
  3690. while (
  3691. marker_length < len(candidate)
  3692. and candidate[marker_length] == marker_character
  3693. ):
  3694. marker_length += 1
  3695. if fence is None and marker_length >= 3:
  3696. fence = (marker_character, marker_length)
  3697. continue
  3698. if fence is not None:
  3699. fence_character, fence_length = fence
  3700. remainder = candidate[marker_length:]
  3701. if (
  3702. marker_character == fence_character
  3703. and marker_length >= fence_length
  3704. and not remainder.strip()
  3705. ):
  3706. fence = None
  3707. continue
  3708. visible.append(line)
  3709. searchable = "".join(visible)
  3710. inline_visible: list[str] = []
  3711. for line in searchable.splitlines(keepends=True):
  3712. index = 0
  3713. while index < len(line):
  3714. if line[index] != "`":
  3715. inline_visible.append(line[index])
  3716. index += 1
  3717. continue
  3718. end = index + 1
  3719. while end < len(line) and line[end] == "`":
  3720. end += 1
  3721. delimiter = line[index:end]
  3722. close = line.find(delimiter, end)
  3723. if close < 0:
  3724. if line.endswith("\n"):
  3725. inline_visible.append("\n")
  3726. break
  3727. index = close + len(delimiter)
  3728. searchable = "".join(inline_visible)
  3729. searchable = re.sub(
  3730. r"(?:[A-Za-z][A-Za-z0-9+.-]*://|www\.)"
  3731. r"[^\s,。!?;:()()\[\]{}]+",
  3732. "",
  3733. searchable,
  3734. flags=re.IGNORECASE,
  3735. )
  3736. return re.sub(r"\\@", "", searchable)
  3737. @staticmethod
  3738. def _mention_word_char(value: str) -> bool:
  3739. return value.isalnum() or value in {"_", ".", "-", "+", "@"}
  3740. @classmethod
  3741. def _mention_end(cls, value: str, end: int) -> bool:
  3742. return end >= len(value) or not cls._mention_word_char(value[end])
  3743. def list_pending_cascades(
  3744. self, *, limit: int = _MAX_CASCADE_PAGE_SIZE, after: int | None = None
  3745. ) -> dict[str, object]:
  3746. if (
  3747. isinstance(limit, bool)
  3748. or not isinstance(limit, int)
  3749. or not (1 <= limit <= _MAX_CASCADE_PAGE_SIZE)
  3750. ):
  3751. raise ValueError("limit must be between 1 and 32")
  3752. if after is None:
  3753. after_value = 0
  3754. elif isinstance(after, bool) or not isinstance(after, int) or after < 0:
  3755. raise ValueError("after must be a non-negative integer")
  3756. else:
  3757. after_value = after
  3758. with self.read_transaction() as connection:
  3759. rows = connection.execute(
  3760. """SELECT rowid, request_id, operation, request_hash, response_json
  3761. FROM group_idempotency
  3762. WHERE operation = ? AND rowid > ?
  3763. ORDER BY rowid ASC LIMIT ?""",
  3764. (_CASCADE_PENDING_OPERATION, after_value, limit + 1),
  3765. ).fetchall()
  3766. validated = [
  3767. (int(row["rowid"]), self._cascade_plan_from_ledger(row)) for row in rows
  3768. ]
  3769. has_more = len(validated) > limit
  3770. validated = validated[:limit]
  3771. items = [{"sourceRunId": plan["sourceRunId"]} for _rowid, plan in validated]
  3772. return {
  3773. "items": items,
  3774. "nextCursor": (validated[-1][0] if has_more and validated else None),
  3775. }
  3776. def _cascade_plan_from_ledger(
  3777. self, ledger: Mapping[str, object]
  3778. ) -> dict[str, object]:
  3779. try:
  3780. request_id = ledger["request_id"]
  3781. operation = ledger["operation"]
  3782. request_hash = ledger["request_hash"]
  3783. encoded = ledger["response_json"]
  3784. except (KeyError, IndexError, TypeError) as error:
  3785. raise GroupStoreError("Stored cascade ledger is corrupt") from error
  3786. prefix = "internal:cascade:"
  3787. if (
  3788. not isinstance(request_id, str)
  3789. or not request_id.startswith(prefix)
  3790. or operation != _CASCADE_PENDING_OPERATION
  3791. or not isinstance(encoded, str)
  3792. or len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES
  3793. ):
  3794. raise GroupStoreError("Stored cascade ledger is corrupt")
  3795. raw_source_id = request_id[len(prefix) :]
  3796. try:
  3797. source_id = self._canonical_uuid(raw_source_id, "sourceRunId")
  3798. except ValueError as error:
  3799. raise GroupStoreError("Stored cascade ledger is corrupt") from error
  3800. if raw_source_id != source_id:
  3801. raise GroupStoreError("Stored cascade ledger is corrupt")
  3802. try:
  3803. plan = self._load_json(encoded)
  3804. except (TypeError, ValueError, json.JSONDecodeError) as error:
  3805. raise GroupStoreError("Stored cascade plan is corrupt") from error
  3806. if not isinstance(plan, dict) or self._canonical_json(plan) != encoded:
  3807. raise GroupStoreError("Stored cascade plan is corrupt")
  3808. parse_version = plan.get("parseVersion")
  3809. if (
  3810. parse_version not in {1, 2, 3}
  3811. or request_hash
  3812. != self._cascade_request_hash(source_id, parse_version=parse_version)
  3813. ):
  3814. raise GroupStoreError("Stored cascade ledger is corrupt")
  3815. common_invalid = (
  3816. plan.get("state") != "pending"
  3817. or plan.get("version") != 1
  3818. or plan.get("sourceRunId") != source_id
  3819. or not isinstance(plan.get("warnings"), list)
  3820. or not all(isinstance(item, dict) for item in plan["warnings"])
  3821. or len(plan["warnings"]) > MAX_AGENTS_PER_ROOM
  3822. )
  3823. if common_invalid:
  3824. raise GroupStoreError("Stored cascade plan is corrupt")
  3825. if parse_version == 1:
  3826. expected_keys = {
  3827. "parseVersion",
  3828. "sourceMessageId",
  3829. "sourceRunId",
  3830. "state",
  3831. "targetAgentIds",
  3832. "version",
  3833. "warnings",
  3834. }
  3835. target_ids = plan.get("targetAgentIds")
  3836. if (
  3837. set(plan) != expected_keys
  3838. or not isinstance(target_ids, list)
  3839. or not all(isinstance(item, str) for item in target_ids)
  3840. ):
  3841. raise GroupStoreError("Stored cascade plan is corrupt")
  3842. targets = [
  3843. {"agentId": item, "replyMode": "mentioned"} for item in target_ids
  3844. ]
  3845. else:
  3846. expected_keys = {
  3847. "parseVersion",
  3848. "sourceMessageId",
  3849. "sourceRunId",
  3850. "state",
  3851. "targets",
  3852. "version",
  3853. "warnings",
  3854. }
  3855. targets = plan.get("targets")
  3856. if (
  3857. set(plan) != expected_keys
  3858. or not isinstance(targets, list)
  3859. or not all(isinstance(item, dict) for item in targets)
  3860. ):
  3861. raise GroupStoreError("Stored cascade plan is corrupt")
  3862. if (
  3863. len(targets) > MAX_AGENTS_PER_ROOM
  3864. or any(set(item) != {"agentId", "replyMode"} for item in targets)
  3865. or any(not isinstance(item.get("agentId"), str) for item in targets)
  3866. or any(item.get("replyMode") not in {"mentioned", "automatic"} for item in targets)
  3867. or len({item.get("agentId") for item in targets}) != len(targets)
  3868. ):
  3869. raise GroupStoreError("Stored cascade plan is corrupt")
  3870. try:
  3871. if (
  3872. self._canonical_uuid(plan["sourceMessageId"], "sourceMessageId")
  3873. != plan["sourceMessageId"]
  3874. ):
  3875. raise ValueError
  3876. for target in targets:
  3877. if (
  3878. self._canonical_uuid(target["agentId"], "targetAgentId")
  3879. != target["agentId"]
  3880. ):
  3881. raise ValueError
  3882. for warning in plan["warnings"]:
  3883. if set(warning) != {"code", "message"} or warning.get("code") != "mention":
  3884. raise ValueError
  3885. self._message_text(
  3886. warning.get("message"),
  3887. "warning.message",
  3888. max_bytes=MAX_MESSAGE_BYTES,
  3889. nonblank=True,
  3890. )
  3891. except (KeyError, TypeError, ValueError) as error:
  3892. raise GroupStoreError("Stored cascade plan is corrupt") from error
  3893. return {
  3894. "parseVersion": parse_version,
  3895. "sourceMessageId": plan["sourceMessageId"],
  3896. "sourceRunId": source_id,
  3897. "state": "pending",
  3898. "targets": targets,
  3899. "version": 1,
  3900. "warnings": plan["warnings"],
  3901. }
  3902. def enqueue_cascade_runs(
  3903. self,
  3904. source_run_id: str,
  3905. *,
  3906. agent_ids: list[str],
  3907. warnings: list[Mapping[str, object]],
  3908. ) -> dict[str, object]:
  3909. """Create bounded, deduplicated Agent cascades and visible warnings."""
  3910. canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
  3911. canonical_agent_ids, requested_warnings = self._validated_cascade_inputs(
  3912. agent_ids, warnings
  3913. )
  3914. with self.write_transaction() as connection:
  3915. source = self._run_row(connection, canonical_source_id)
  3916. self._active_room(connection, source["room_id"])
  3917. self._enabled_agent(connection, source["room_id"], source["agent_id"])
  3918. if source["status"] != "completed":
  3919. raise GroupConflictError("Cascade source run must be completed")
  3920. source_message = self._message_row(
  3921. connection, source["response_message_id"]
  3922. )
  3923. if source_message["status"] != "completed":
  3924. raise GroupConflictError("Cascade source message must be completed")
  3925. return self._enqueue_cascade_runs_transaction(
  3926. connection,
  3927. source=source,
  3928. canonical_agent_ids=canonical_agent_ids,
  3929. requested_warnings=requested_warnings,
  3930. now=self._now(),
  3931. )
  3932. def _validated_cascade_inputs(
  3933. self,
  3934. agent_ids: object,
  3935. warnings: object,
  3936. ) -> tuple[list[str], list[str]]:
  3937. if not isinstance(agent_ids, list):
  3938. raise ValueError("agent_ids must be a list")
  3939. if len(agent_ids) > MAX_AGENTS_PER_ROOM:
  3940. raise ValueError(
  3941. f"agent_ids must contain at most {MAX_AGENTS_PER_ROOM} entries"
  3942. )
  3943. canonical_agent_ids: list[str] = []
  3944. seen_agent_ids: set[str] = set()
  3945. for value in agent_ids:
  3946. agent_id = self._canonical_uuid(value, "agentId")
  3947. if agent_id not in seen_agent_ids:
  3948. seen_agent_ids.add(agent_id)
  3949. canonical_agent_ids.append(agent_id)
  3950. if not isinstance(warnings, list):
  3951. raise ValueError("warnings must be a list of objects")
  3952. if len(warnings) > MAX_AGENTS_PER_ROOM:
  3953. raise ValueError(
  3954. f"warnings must contain at most {MAX_AGENTS_PER_ROOM} entries"
  3955. )
  3956. if not all(isinstance(item, Mapping) for item in warnings):
  3957. raise ValueError("warnings must be a list of objects")
  3958. warnings_json = self._strict_json(
  3959. [dict(warning) for warning in warnings], "warnings"
  3960. )
  3961. if len(warnings_json.encode("utf-8")) > MAX_MESSAGE_BYTES:
  3962. raise ValueError("warnings exceed maximum size")
  3963. requested_warnings: list[str] = []
  3964. for warning in warnings:
  3965. message = warning.get("message")
  3966. requested_warnings.append(
  3967. self._message_text(
  3968. message,
  3969. "warning.message",
  3970. max_bytes=MAX_MESSAGE_BYTES,
  3971. nonblank=True,
  3972. )
  3973. )
  3974. return canonical_agent_ids, requested_warnings
  3975. def complete_cascade(self, source_run_id: str) -> dict[str, object]:
  3976. """Execute one frozen Mention plan exactly once and terminalize it."""
  3977. canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
  3978. request_id = self._cascade_request_id(canonical_source_id)
  3979. expected_hashes = {
  3980. self._cascade_request_hash(canonical_source_id, parse_version=1),
  3981. self._cascade_request_hash(canonical_source_id, parse_version=2),
  3982. self._cascade_request_hash(canonical_source_id, parse_version=3),
  3983. }
  3984. with self.write_transaction() as connection:
  3985. ledger = connection.execute(
  3986. """SELECT request_id, operation, request_hash, response_json
  3987. FROM group_idempotency WHERE request_id = ?""",
  3988. (request_id,),
  3989. ).fetchone()
  3990. if ledger is None:
  3991. raise GroupNotFoundError("Cascade source not found")
  3992. if (
  3993. ledger["operation"] not in _CASCADE_OPERATIONS
  3994. or ledger["request_hash"] not in expected_hashes
  3995. ):
  3996. raise GroupStoreError("Stored cascade ledger is corrupt")
  3997. if ledger["operation"] != _CASCADE_PENDING_OPERATION:
  3998. return self._cascade_result(
  3999. ledger["response_json"], ledger["operation"]
  4000. )
  4001. plan = self._cascade_plan_from_ledger(ledger)
  4002. source = connection.execute(
  4003. "SELECT * FROM group_agent_runs WHERE id = ?",
  4004. (canonical_source_id,),
  4005. ).fetchone()
  4006. if source is None:
  4007. raise GroupStoreError("Stored cascade source is missing")
  4008. room = connection.execute(
  4009. "SELECT archived, orchestration_mode FROM group_rooms WHERE id = ?",
  4010. (source["room_id"],),
  4011. ).fetchone()
  4012. source_agent = connection.execute(
  4013. "SELECT enabled, is_host FROM group_agents WHERE id = ? AND room_id = ?",
  4014. (source["agent_id"], source["room_id"]),
  4015. ).fetchone()
  4016. if room is None:
  4017. raise GroupStoreError("Stored cascade ownership is corrupt")
  4018. source_message = self._message_row(
  4019. connection, source["response_message_id"]
  4020. )
  4021. host_flow_member_terminal = (
  4022. room["orchestration_mode"] == "host"
  4023. and source_agent is not None
  4024. and not source_agent["is_host"]
  4025. and source["status"] in {"completed", "failed", "interrupted"}
  4026. )
  4027. if source["status"] != "completed" and not host_flow_member_terminal:
  4028. raise GroupStoreError("Stored cascade source is not terminal")
  4029. if source_message["id"] != plan["sourceMessageId"]:
  4030. raise GroupStoreError("Stored cascade message is corrupt")
  4031. self._validate_run_message_status(
  4032. str(source["status"]), str(source_message["status"])
  4033. )
  4034. if room["archived"] or source_agent is None or not source_agent["enabled"]:
  4035. result = self._cascade_summary([], [], state="discarded")
  4036. connection.execute(
  4037. """UPDATE group_idempotency
  4038. SET operation = ?, response_json = ? WHERE request_id = ?""",
  4039. (
  4040. _CASCADE_DISCARDED_OPERATION,
  4041. self._canonical_json(result),
  4042. request_id,
  4043. ),
  4044. )
  4045. return result
  4046. try:
  4047. canonical_ids, warning_texts = self._validated_cascade_inputs(
  4048. [target["agentId"] for target in plan["targets"]],
  4049. plan["warnings"],
  4050. )
  4051. reply_modes = {
  4052. target["agentId"]: target["replyMode"]
  4053. for target in plan["targets"]
  4054. }
  4055. except ValueError as error:
  4056. raise GroupStoreError("Stored cascade plan is corrupt") from error
  4057. created = self._enqueue_cascade_runs_transaction(
  4058. connection,
  4059. source=source,
  4060. canonical_agent_ids=canonical_ids,
  4061. requested_warnings=warning_texts,
  4062. reply_modes=reply_modes,
  4063. now=self._now(),
  4064. )
  4065. result = self._cascade_summary(
  4066. created["runs"], created["systemMessages"], state="completed"
  4067. )
  4068. connection.execute(
  4069. """UPDATE group_idempotency
  4070. SET operation = ?, response_json = ? WHERE request_id = ?""",
  4071. (
  4072. _CASCADE_COMPLETED_OPERATION,
  4073. self._canonical_json(result),
  4074. request_id,
  4075. ),
  4076. )
  4077. return result
  4078. @classmethod
  4079. def _cascade_result(cls, encoded: object, operation: str) -> dict[str, object]:
  4080. try:
  4081. result = cls._load_json(encoded)
  4082. except (TypeError, ValueError, json.JSONDecodeError) as error:
  4083. raise GroupStoreError("Stored cascade result is corrupt") from error
  4084. expected_state = (
  4085. "completed" if operation == _CASCADE_COMPLETED_OPERATION else "discarded"
  4086. )
  4087. expected_keys = {
  4088. "runCount",
  4089. "runIds",
  4090. "state",
  4091. "systemMessageCount",
  4092. "systemMessageIds",
  4093. }
  4094. if expected_state == "discarded":
  4095. expected_keys.add("discarded")
  4096. if (
  4097. not isinstance(result, dict)
  4098. or cls._canonical_json(result) != encoded
  4099. or set(result) != expected_keys
  4100. or result.get("state") != expected_state
  4101. or not isinstance(result.get("runIds"), list)
  4102. or not all(isinstance(item, str) for item in result["runIds"])
  4103. or len(result["runIds"]) > MAX_AGENTS_PER_ROOM
  4104. or len(result["runIds"]) != len(set(result["runIds"]))
  4105. or type(result.get("runCount")) is not int
  4106. or result.get("runCount") != len(result["runIds"])
  4107. or not isinstance(result.get("systemMessageIds"), list)
  4108. or not all(isinstance(item, str) for item in result["systemMessageIds"])
  4109. or len(result["systemMessageIds"]) > MAX_AGENTS_PER_ROOM
  4110. or len(result["systemMessageIds"]) != len(set(result["systemMessageIds"]))
  4111. or type(result.get("systemMessageCount")) is not int
  4112. or result.get("systemMessageCount") != len(result["systemMessageIds"])
  4113. or (expected_state == "discarded") != (result.get("discarded") is True)
  4114. ):
  4115. raise GroupStoreError("Stored cascade result is corrupt")
  4116. try:
  4117. if any(
  4118. cls._canonical_uuid(item, "runId") != item for item in result["runIds"]
  4119. ) or any(
  4120. cls._canonical_uuid(item, "messageId") != item
  4121. for item in result["systemMessageIds"]
  4122. ):
  4123. raise ValueError
  4124. except ValueError as error:
  4125. raise GroupStoreError("Stored cascade result is corrupt") from error
  4126. return result
  4127. @staticmethod
  4128. def _cascade_summary(
  4129. runs: list[Mapping[str, object]],
  4130. messages: list[Mapping[str, object]],
  4131. *,
  4132. state: str,
  4133. ) -> dict[str, object]:
  4134. result: dict[str, object] = {
  4135. "runCount": len(runs),
  4136. "runIds": [run["id"] for run in runs],
  4137. "state": state,
  4138. "systemMessageCount": len(messages),
  4139. "systemMessageIds": [message["id"] for message in messages],
  4140. }
  4141. if state == "discarded":
  4142. result["discarded"] = True
  4143. return result
  4144. def _enqueue_cascade_runs_transaction(
  4145. self,
  4146. connection: sqlite3.Connection,
  4147. *,
  4148. source: sqlite3.Row,
  4149. canonical_agent_ids: list[str],
  4150. requested_warnings: list[str],
  4151. now: float,
  4152. reply_modes: Mapping[str, str] | None = None,
  4153. ) -> dict[str, list[dict[str, object]]]:
  4154. room = self._active_room(connection, source["room_id"])
  4155. room_agents = connection.execute(
  4156. """SELECT * FROM group_agents WHERE room_id = ?
  4157. ORDER BY created_at ASC, id ASC""",
  4158. (source["room_id"],),
  4159. ).fetchall()
  4160. agents_by_id = {agent["id"]: agent for agent in room_agents}
  4161. warning_texts = list(requested_warnings)
  4162. source_agent = agents_by_id.get(source["agent_id"])
  4163. if source_agent is None:
  4164. raise GroupStoreError("Cascade source Agent is missing")
  4165. host_review = (
  4166. room["orchestration_mode"] == "host" and not source_agent["is_host"]
  4167. )
  4168. next_depth = int(source["depth"]) + (0 if host_review else 1)
  4169. max_reply_rounds = int(room["max_reply_rounds"])
  4170. if max_reply_rounds != -1 and next_depth >= max_reply_rounds:
  4171. warning_texts.append("Cascade depth limit reached")
  4172. canonical_agent_ids = []
  4173. source_message = self._message_row(connection, source["response_message_id"])
  4174. trigger_message_id = str(source["response_message_id"])
  4175. if host_review:
  4176. current_host = next(
  4177. (agent for agent in room_agents if agent["is_host"] and agent["enabled"]),
  4178. None,
  4179. )
  4180. if current_host is None:
  4181. raise GroupStoreError("Host flow has no enabled host Agent")
  4182. canonical_agent_ids = [str(current_host["id"])]
  4183. reply_modes = {str(current_host["id"]): "automatic"}
  4184. unfinished_sibling = connection.execute(
  4185. """SELECT 1 FROM group_agent_runs
  4186. WHERE topic_id = ? AND root_message_id = ? AND depth = ?
  4187. AND trigger_message_id = ? AND id != ?
  4188. AND status NOT IN ('completed', 'failed', 'interrupted')
  4189. LIMIT 1""",
  4190. (
  4191. source["topic_id"],
  4192. source["root_message_id"],
  4193. source["depth"],
  4194. source["trigger_message_id"],
  4195. source["id"],
  4196. ),
  4197. ).fetchone()
  4198. if unfinished_sibling is not None:
  4199. return {"runs": [], "systemMessages": []}
  4200. existing_review = connection.execute(
  4201. """SELECT 1 FROM group_agent_runs
  4202. WHERE topic_id = ? AND root_message_id = ? AND depth = ?
  4203. AND agent_id = ? LIMIT 1""",
  4204. (
  4205. source["topic_id"],
  4206. source["root_message_id"],
  4207. next_depth,
  4208. current_host["id"],
  4209. ),
  4210. ).fetchone()
  4211. if existing_review is not None:
  4212. return {"runs": [], "systemMessages": []}
  4213. barrier = connection.execute(
  4214. """SELECT id FROM group_messages
  4215. WHERE room_id = ? AND topic_id = ? AND root_message_id = ?
  4216. AND reply_to_message_id = ? AND sender_kind = 'system'
  4217. AND visible = 0 AND content = ? AND status = 'completed'
  4218. ORDER BY seq ASC LIMIT 1""",
  4219. (
  4220. source["room_id"],
  4221. source["topic_id"],
  4222. source["root_message_id"],
  4223. source["trigger_message_id"],
  4224. _HOST_FLOW_BARRIER_CONTENT,
  4225. ),
  4226. ).fetchone()
  4227. if barrier is None:
  4228. barrier_id = str(uuid.uuid4())
  4229. connection.execute(
  4230. """INSERT INTO group_messages
  4231. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  4232. root_message_id, reply_to_message_id, client_message_id,
  4233. content, reasoning, tool_state_json, status, error, visible,
  4234. created_at, updated_at)
  4235. VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
  4236. ?, '', '[]', 'completed', '', 0, ?, ?)""",
  4237. (
  4238. barrier_id,
  4239. source["room_id"],
  4240. source["topic_id"],
  4241. source["root_message_id"],
  4242. source["trigger_message_id"],
  4243. _HOST_FLOW_BARRIER_CONTENT,
  4244. now,
  4245. now,
  4246. ),
  4247. )
  4248. trigger_message_id = barrier_id
  4249. else:
  4250. trigger_message_id = str(barrier["id"])
  4251. explicit_ids, _ = self._plan_cascade_mentions(
  4252. source_message["content"],
  4253. room_agents,
  4254. source_agent_id=source["agent_id"],
  4255. include_automatic=False,
  4256. )
  4257. explicit_set = set(explicit_ids)
  4258. created_runs: list[dict[str, object]] = []
  4259. for agent_id in canonical_agent_ids:
  4260. agent = agents_by_id.get(agent_id)
  4261. if agent is None:
  4262. warning_texts.append(f"Unknown Agent: {agent_id}")
  4263. continue
  4264. if not agent["enabled"]:
  4265. warning_texts.append(f"Agent disabled: {agent['display_name']}")
  4266. continue
  4267. duplicate = connection.execute(
  4268. """SELECT 1 FROM group_agent_runs
  4269. WHERE room_id = ? AND topic_id = ? AND root_message_id = ?
  4270. AND agent_id = ? AND depth = ? LIMIT 1""",
  4271. (
  4272. source["room_id"],
  4273. source["topic_id"],
  4274. source["root_message_id"],
  4275. agent_id,
  4276. next_depth,
  4277. ),
  4278. ).fetchone()
  4279. if duplicate is not None:
  4280. continue
  4281. reply_mode = (
  4282. reply_modes.get(agent_id, "mentioned")
  4283. if reply_modes is not None
  4284. else ("mentioned" if agent_id in explicit_set else "automatic")
  4285. )
  4286. if reply_mode not in {"mentioned", "automatic"}:
  4287. raise GroupStoreError("Stored cascade plan is corrupt")
  4288. required_reply = bool(host_review and agent["is_host"])
  4289. visible = reply_mode == "mentioned" or required_reply
  4290. response_id = str(uuid.uuid4())
  4291. run_id = str(uuid.uuid4())
  4292. connection.execute(
  4293. """INSERT INTO group_messages
  4294. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  4295. root_message_id, reply_to_message_id, client_message_id,
  4296. content, reasoning, tool_state_json, status, error, visible,
  4297. created_at, updated_at)
  4298. VALUES (?, ?, ?, 'agent', ?, ?, ?, ?, NULL,
  4299. '', '', '[]', 'queued', '', ?, ?, ?)""",
  4300. (
  4301. response_id,
  4302. source["room_id"],
  4303. source["topic_id"],
  4304. agent_id,
  4305. agent["display_name"],
  4306. source["root_message_id"],
  4307. trigger_message_id,
  4308. int(visible),
  4309. now,
  4310. now,
  4311. ),
  4312. )
  4313. connection.execute(
  4314. """INSERT INTO group_agent_runs
  4315. (id, room_id, topic_id, agent_id, trigger_message_id,
  4316. response_message_id, root_message_id, depth, reply_mode,
  4317. required_reply, status, runtime_session_id, requested_model,
  4318. requested_provider, requested_reasoning_effort,
  4319. requested_fast_mode, actual_model, actual_provider,
  4320. actual_reasoning_effort, actual_fast_mode, error, created_at,
  4321. updated_at)
  4322. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL,
  4323. ?, ?, ?, ?, NULL, NULL, NULL, NULL, '', ?, ?)""",
  4324. (
  4325. run_id,
  4326. source["room_id"],
  4327. source["topic_id"],
  4328. agent_id,
  4329. trigger_message_id,
  4330. response_id,
  4331. source["root_message_id"],
  4332. next_depth,
  4333. reply_mode,
  4334. int(required_reply),
  4335. agent["model_override"],
  4336. agent["provider_override"],
  4337. agent["reasoning_effort_override"],
  4338. agent["fast_mode_override"],
  4339. now,
  4340. now,
  4341. ),
  4342. )
  4343. message = self._message_wire(self._message_row(connection, response_id))
  4344. run = self._run_wire(self._run_row(connection, run_id))
  4345. if visible:
  4346. self._append_event(
  4347. connection,
  4348. source["room_id"],
  4349. "message.upsert",
  4350. message,
  4351. created_at=now,
  4352. )
  4353. self._append_event(
  4354. connection,
  4355. source["room_id"],
  4356. "run.updated",
  4357. run,
  4358. created_at=now,
  4359. )
  4360. created_runs.append(run)
  4361. if (
  4362. room["orchestration_mode"] == "host"
  4363. and source_agent["is_host"]
  4364. and created_runs
  4365. ):
  4366. barrier_id = str(uuid.uuid4())
  4367. connection.execute(
  4368. """INSERT INTO group_messages
  4369. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  4370. root_message_id, reply_to_message_id, client_message_id,
  4371. content, reasoning, tool_state_json, status, error, visible,
  4372. created_at, updated_at)
  4373. VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
  4374. ?, '', '[]', 'completed', '', 0, ?, ?)""",
  4375. (
  4376. barrier_id,
  4377. source["room_id"],
  4378. source["topic_id"],
  4379. source["root_message_id"],
  4380. source["response_message_id"],
  4381. _HOST_FLOW_BARRIER_CONTENT,
  4382. now,
  4383. now,
  4384. ),
  4385. )
  4386. system_messages: list[dict[str, object]] = []
  4387. for warning_text in list(dict.fromkeys(warning_texts))[:MAX_AGENTS_PER_ROOM]:
  4388. duplicate = connection.execute(
  4389. """SELECT * FROM group_messages
  4390. WHERE room_id = ? AND topic_id = ? AND sender_kind = 'system'
  4391. AND root_message_id = ? AND reply_to_message_id = ?
  4392. AND content = ? AND status = 'completed'
  4393. ORDER BY seq ASC LIMIT 1""",
  4394. (
  4395. source["room_id"],
  4396. source["topic_id"],
  4397. source["root_message_id"],
  4398. source["response_message_id"],
  4399. warning_text,
  4400. ),
  4401. ).fetchone()
  4402. if duplicate is not None:
  4403. continue
  4404. message_id = str(uuid.uuid4())
  4405. connection.execute(
  4406. """INSERT INTO group_messages
  4407. (id, room_id, topic_id, sender_kind, sender_id, sender_name,
  4408. root_message_id, reply_to_message_id, client_message_id,
  4409. content, reasoning, tool_state_json, status, error,
  4410. created_at, updated_at)
  4411. VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
  4412. ?, '', '[]', 'completed', '', ?, ?)""",
  4413. (
  4414. message_id,
  4415. source["room_id"],
  4416. source["topic_id"],
  4417. source["root_message_id"],
  4418. source["response_message_id"],
  4419. warning_text,
  4420. now,
  4421. now,
  4422. ),
  4423. )
  4424. message = self._message_wire(self._message_row(connection, message_id))
  4425. self._append_event(
  4426. connection,
  4427. source["room_id"],
  4428. "message.upsert",
  4429. message,
  4430. created_at=now,
  4431. )
  4432. system_messages.append(message)
  4433. return {"runs": created_runs, "systemMessages": system_messages}
  4434. def upsert_agent_message(
  4435. self,
  4436. run_id: str,
  4437. *,
  4438. content: str,
  4439. reasoning: str,
  4440. tool_state: object,
  4441. status: str,
  4442. error: str = "",
  4443. publish: bool = True,
  4444. ) -> dict[str, object]:
  4445. canonical_run_id = self._canonical_uuid(run_id, "runId")
  4446. content = self._message_text(content, "content", max_bytes=MAX_MESSAGE_BYTES)
  4447. reasoning = self._message_text(
  4448. reasoning, "reasoning", max_bytes=MAX_MESSAGE_BYTES
  4449. )
  4450. error = self._message_text(error, "error", max_bytes=4096)
  4451. if not isinstance(status, str) or status not in _MESSAGE_STATUSES:
  4452. raise ValueError("status is invalid")
  4453. tool_json = self._tool_state_json(tool_state)
  4454. with self.write_transaction() as connection:
  4455. run = self._run_row(connection, canonical_run_id)
  4456. self._active_room(connection, run["room_id"])
  4457. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  4458. response = self._message_row(connection, run["response_message_id"])
  4459. if (
  4460. response["room_id"] != run["room_id"]
  4461. or response["sender_id"] != run["agent_id"]
  4462. ):
  4463. raise GroupStoreError("Run response message is corrupt")
  4464. self._validate_run_message_state(run, response)
  4465. if status not in _AGENT_MESSAGE_STATUSES_BY_RUN[run["status"]]:
  4466. raise GroupConflictError("Message status is invalid for run state")
  4467. if status not in _AGENT_MESSAGE_TRANSITIONS.get(
  4468. response["status"], frozenset()
  4469. ):
  4470. raise GroupConflictError("Message status cannot move backwards")
  4471. now = self._now()
  4472. visible = bool(response["visible"]) or publish
  4473. connection.execute(
  4474. """UPDATE group_messages SET content = ?, reasoning = ?, tool_state_json = ?,
  4475. status = ?, error = ?, visible = ?, updated_at = ? WHERE id = ?""",
  4476. (
  4477. content,
  4478. reasoning,
  4479. tool_json,
  4480. status,
  4481. error,
  4482. int(visible),
  4483. now,
  4484. run["response_message_id"],
  4485. ),
  4486. )
  4487. message = self._message_wire(
  4488. self._message_row(connection, run["response_message_id"])
  4489. )
  4490. if visible:
  4491. self._append_event(
  4492. connection,
  4493. run["room_id"],
  4494. "message.upsert",
  4495. message,
  4496. created_at=now,
  4497. )
  4498. return message
  4499. def transition_run(
  4500. self,
  4501. run_id: str,
  4502. status: str,
  4503. *,
  4504. runtime_session_id: object = UNSET,
  4505. error: object = UNSET,
  4506. ) -> dict[str, object]:
  4507. canonical_run_id = self._canonical_uuid(run_id, "runId")
  4508. if not isinstance(status, str) or status not in RUN_TRANSITIONS:
  4509. raise ValueError("status is invalid")
  4510. runtime_value = (
  4511. self._runtime_session_id(runtime_session_id)
  4512. if runtime_session_id is not UNSET
  4513. else UNSET
  4514. )
  4515. error_value = (
  4516. self._message_text(error, "error", max_bytes=4096)
  4517. if error is not UNSET
  4518. else UNSET
  4519. )
  4520. with self.write_transaction() as connection:
  4521. run = self._run_row(connection, canonical_run_id)
  4522. room = self._active_room(connection, run["room_id"])
  4523. agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
  4524. response = self._message_row(connection, run["response_message_id"])
  4525. if (
  4526. response["room_id"] != run["room_id"]
  4527. or response["sender_id"] != run["agent_id"]
  4528. ):
  4529. raise GroupStoreError("Run response message is corrupt")
  4530. self._validate_run_message_state(run, response)
  4531. if status == run["status"]:
  4532. if status == "running":
  4533. if (
  4534. runtime_value is not UNSET
  4535. and runtime_value is not None
  4536. and run["runtime_session_id"] is not None
  4537. and runtime_value == run["runtime_session_id"]
  4538. ):
  4539. return self._run_wire(run)
  4540. raise GroupConflictError("Run is already claimed")
  4541. return self._run_wire(run)
  4542. if status not in RUN_TRANSITIONS[run["status"]]:
  4543. raise GroupConflictError("Illegal run status transition")
  4544. if status == "completed" and response["status"] != "completed":
  4545. raise GroupConflictError("Response message must be completed first")
  4546. if status not in {"failed", "interrupted"}:
  4547. self._validate_run_message_status(status, response["status"])
  4548. now = self._now()
  4549. if status in {"completed", "failed", "interrupted"}:
  4550. self._cancel_pending_interactions(connection, run, now)
  4551. result = self._update_run(
  4552. connection, run, status, now, runtime_value, error_value
  4553. )
  4554. if status in {"completed", "failed", "interrupted"}:
  4555. self._fail_claimed_interaction_ledgers(
  4556. connection,
  4557. run_id=run["id"],
  4558. reason=result["error"] or f"Run {status}",
  4559. runtime_session_ids=(
  4560. []
  4561. if run["runtime_session_id"] is None
  4562. else [run["runtime_session_id"]]
  4563. ),
  4564. run=result,
  4565. )
  4566. self._append_event(
  4567. connection, result["roomId"], "run.updated", result, created_at=now
  4568. )
  4569. if status in {"failed", "interrupted"}:
  4570. if response["status"] == "completed":
  4571. self._validate_run_message_status(status, response["status"])
  4572. else:
  4573. terminal_error = result["error"]
  4574. connection.execute(
  4575. """UPDATE group_messages
  4576. SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
  4577. (status, terminal_error, now, run["response_message_id"]),
  4578. )
  4579. message = self._message_wire(
  4580. self._message_row(connection, run["response_message_id"])
  4581. )
  4582. self._validate_run_message_status(
  4583. result["status"], message["status"]
  4584. )
  4585. if message["visible"]:
  4586. self._append_event(
  4587. connection,
  4588. result["roomId"],
  4589. "message.upsert",
  4590. message,
  4591. created_at=now,
  4592. )
  4593. if status == "completed" or (
  4594. room["orchestration_mode"] == "host" and not agent["is_host"]
  4595. ):
  4596. self._record_cascade_plan(
  4597. connection,
  4598. source=self._run_row(connection, run["id"]),
  4599. source_message=self._message_row(
  4600. connection, run["response_message_id"]
  4601. ),
  4602. created_at=now,
  4603. )
  4604. return result
  4605. def bind_run_runtime(
  4606. self, run_id: str, runtime_session_id: str
  4607. ) -> dict[str, object]:
  4608. """Bind the first real runtime identity without reopening the run claim."""
  4609. canonical_run_id = self._canonical_uuid(run_id, "runId")
  4610. runtime_value = self._runtime_session_id(runtime_session_id)
  4611. if runtime_value is None:
  4612. raise ValueError("runtimeSessionId is invalid")
  4613. with self.write_transaction() as connection:
  4614. run = self._run_row(connection, canonical_run_id)
  4615. self._active_room(connection, run["room_id"])
  4616. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  4617. response = self._message_row(connection, run["response_message_id"])
  4618. self._validate_run_message_state(run, response)
  4619. if run["status"] not in {"running", "awaiting_input"}:
  4620. raise GroupConflictError("Run does not accept a runtime binding")
  4621. if run["runtime_session_id"] == runtime_value:
  4622. return self._run_wire(run)
  4623. if run["runtime_session_id"] is not None:
  4624. raise GroupConflictError("Run runtime is already bound")
  4625. self._require_available_runtime(connection, runtime_value, canonical_run_id)
  4626. now = self._now()
  4627. result = self._update_run(
  4628. connection, run, run["status"], now, runtime_value, UNSET
  4629. )
  4630. self._append_event(
  4631. connection, run["room_id"], "run.updated", result, created_at=now
  4632. )
  4633. return result
  4634. def create_interaction(
  4635. self,
  4636. interaction_id: str,
  4637. run_id: str,
  4638. *,
  4639. kind: str,
  4640. payload: object,
  4641. ) -> dict[str, object]:
  4642. return self._create_gateway_interaction(
  4643. run_id,
  4644. kind=kind,
  4645. gateway_interaction_id=interaction_id,
  4646. payload=payload,
  4647. allow_awaiting=False,
  4648. )
  4649. def create_gateway_interaction(
  4650. self,
  4651. run_id: str,
  4652. *,
  4653. kind: str,
  4654. gateway_interaction_id: str | None,
  4655. payload: object,
  4656. ) -> dict[str, object]:
  4657. return self._create_gateway_interaction(
  4658. run_id,
  4659. kind=kind,
  4660. gateway_interaction_id=gateway_interaction_id,
  4661. payload=payload,
  4662. allow_awaiting=True,
  4663. )
  4664. def _create_gateway_interaction(
  4665. self,
  4666. run_id: str,
  4667. *,
  4668. kind: str,
  4669. gateway_interaction_id: str | None,
  4670. payload: object,
  4671. allow_awaiting: bool,
  4672. ) -> dict[str, object]:
  4673. canonical_run_id = self._canonical_uuid(run_id, "runId")
  4674. if not isinstance(kind, str) or kind not in _INTERACTION_KINDS:
  4675. raise ValueError("kind is invalid")
  4676. payload_json = self._json_object(payload, "payload")
  4677. payload_value = self._load_json(payload_json)
  4678. clarification_gateway_id: str | None = None
  4679. if kind == "approval" and gateway_interaction_id is None:
  4680. interaction_id = f"approval-{uuid.uuid4()}"
  4681. elif gateway_interaction_id is None:
  4682. raise ValueError("Gateway clarification interactionId is required")
  4683. else:
  4684. gateway_id = self._interaction_id(gateway_interaction_id)
  4685. if kind == "clarification" and allow_awaiting:
  4686. if "gatewayRequestId" in payload_value:
  4687. raise ValueError("payload.gatewayRequestId is reserved")
  4688. payload_value["gatewayRequestId"] = gateway_id
  4689. payload_json = self._json_object(payload_value, "payload")
  4690. clarification_gateway_id = gateway_id
  4691. interaction_id = None
  4692. else:
  4693. interaction_id = gateway_id
  4694. try:
  4695. with self.write_transaction() as connection:
  4696. run = self._run_row(connection, canonical_run_id)
  4697. self._active_room(connection, run["room_id"])
  4698. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  4699. response = self._message_row(connection, run["response_message_id"])
  4700. self._validate_run_message_state(run, response)
  4701. accepted_statuses = (
  4702. {"running", "awaiting_input"} if allow_awaiting else {"running"}
  4703. )
  4704. if run["status"] not in accepted_statuses:
  4705. raise GroupConflictError("Interaction requires a running run")
  4706. self._validate_run_message_status("awaiting_input", response["status"])
  4707. if clarification_gateway_id is not None:
  4708. pending = connection.execute(
  4709. """SELECT * FROM group_interactions
  4710. WHERE run_id = ? AND kind = 'clarification'
  4711. AND status = 'pending' ORDER BY rowid ASC""",
  4712. (canonical_run_id,),
  4713. ).fetchall()
  4714. matching = []
  4715. for candidate in pending:
  4716. candidate_wire = self._interaction_wire(candidate)
  4717. if (
  4718. candidate_wire["payload"].get("gatewayRequestId")
  4719. == clarification_gateway_id
  4720. ):
  4721. matching.append(candidate)
  4722. if len(matching) > 1:
  4723. raise GroupStoreError(
  4724. "Stored clarification identities are not unique"
  4725. )
  4726. if matching:
  4727. existing = matching[0]
  4728. if existing["payload_json"] != payload_json:
  4729. raise GroupConflictError("Interaction already exists")
  4730. return self._interaction_wire(existing)
  4731. interaction_id = f"clarification-{uuid.uuid4()}"
  4732. if interaction_id is None:
  4733. raise GroupStoreError("Interaction identity is missing")
  4734. existing = connection.execute(
  4735. "SELECT * FROM group_interactions WHERE id = ?",
  4736. (interaction_id,),
  4737. ).fetchone()
  4738. if existing is not None:
  4739. if (
  4740. existing["room_id"] != run["room_id"]
  4741. or existing["agent_id"] != run["agent_id"]
  4742. or existing["run_id"] != canonical_run_id
  4743. or existing["kind"] != kind
  4744. or existing["payload_json"] != payload_json
  4745. ):
  4746. raise GroupConflictError("Interaction already exists")
  4747. return self._interaction_wire(existing)
  4748. now = self._now()
  4749. connection.execute(
  4750. """INSERT INTO group_interactions
  4751. (id, room_id, topic_id, agent_id, run_id, kind, payload_json, status, created_at, resolved_at)
  4752. VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL)""",
  4753. (
  4754. interaction_id,
  4755. run["room_id"],
  4756. run["topic_id"],
  4757. run["agent_id"],
  4758. canonical_run_id,
  4759. kind,
  4760. payload_json,
  4761. now,
  4762. ),
  4763. )
  4764. interaction = self._interaction_wire(
  4765. self._interaction_row(connection, interaction_id)
  4766. )
  4767. self._append_event(
  4768. connection,
  4769. run["room_id"],
  4770. "interaction.requested",
  4771. interaction,
  4772. created_at=now,
  4773. )
  4774. if run["status"] == "running":
  4775. changed = self._update_run(
  4776. connection, run, "awaiting_input", now, UNSET, UNSET
  4777. )
  4778. self._append_event(
  4779. connection,
  4780. run["room_id"],
  4781. "run.updated",
  4782. changed,
  4783. created_at=now,
  4784. )
  4785. return interaction
  4786. except sqlite3.IntegrityError as error:
  4787. if "group_interactions.id" in str(error):
  4788. raise GroupConflictError("Interaction already exists") from error
  4789. raise self._integrity_conflict(error) from error
  4790. def resolve_interaction(
  4791. self, interaction_id: str, *, status: str = "resolved"
  4792. ) -> dict[str, object]:
  4793. interaction_id = self._interaction_id(interaction_id)
  4794. if not isinstance(status, str) or status not in _INTERACTION_TERMINAL_STATUSES:
  4795. raise ValueError("status must be resolved or cancelled")
  4796. with self.write_transaction() as connection:
  4797. interaction = self._interaction_row(connection, interaction_id)
  4798. if interaction["status"] != "pending":
  4799. raise GroupConflictError("Interaction is already resolved")
  4800. run = self._run_row(connection, interaction["run_id"])
  4801. self._active_room(connection, run["room_id"])
  4802. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  4803. response = self._message_row(connection, run["response_message_id"])
  4804. self._validate_run_message_state(run, response)
  4805. now = self._now()
  4806. connection.execute(
  4807. "UPDATE group_interactions SET status = ?, resolved_at = ? WHERE id = ?",
  4808. (status, now, interaction_id),
  4809. )
  4810. result = self._interaction_wire(
  4811. self._interaction_row(connection, interaction_id)
  4812. )
  4813. self._append_event(
  4814. connection,
  4815. result["roomId"],
  4816. "interaction.resolved",
  4817. result,
  4818. created_at=now,
  4819. )
  4820. if status == "resolved":
  4821. if run["status"] != "awaiting_input":
  4822. raise GroupConflictError("Interaction run is not awaiting input")
  4823. remaining = connection.execute(
  4824. """SELECT 1 FROM group_interactions
  4825. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  4826. (run["id"],),
  4827. ).fetchone()
  4828. if remaining is None:
  4829. self._validate_run_message_status("running", response["status"])
  4830. changed = self._update_run(
  4831. connection, run, "running", now, UNSET, UNSET
  4832. )
  4833. self._append_event(
  4834. connection,
  4835. changed["roomId"],
  4836. "run.updated",
  4837. changed,
  4838. created_at=now,
  4839. )
  4840. run_result = changed
  4841. else:
  4842. run_result = self._run_wire(run)
  4843. else:
  4844. run_result = self._run_wire(run)
  4845. self._fail_claimed_interaction_ledgers(
  4846. connection,
  4847. run_id=run["id"],
  4848. interaction_id=interaction_id,
  4849. reason=f"Interaction {status}",
  4850. runtime_session_ids=(
  4851. []
  4852. if run["runtime_session_id"] is None
  4853. else [run["runtime_session_id"]]
  4854. ),
  4855. run=run_result,
  4856. )
  4857. return result
  4858. def begin_interaction_response(
  4859. self,
  4860. room_id: str,
  4861. interaction_id: str,
  4862. *,
  4863. request_id: str,
  4864. kind: str,
  4865. response: Mapping[str, object],
  4866. ) -> dict[str, object]:
  4867. """Durably claim one FIFO Gateway response without a public status."""
  4868. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  4869. interaction_id = self._interaction_id(interaction_id)
  4870. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  4871. if kind not in _INTERACTION_KINDS:
  4872. raise ValueError("kind is invalid")
  4873. response_json = self._json_object(response, "response")
  4874. response_value = self._load_json(response_json)
  4875. legacy_operation = f"interaction.{kind}.response"
  4876. operation = self._interaction_operation(kind, interaction_id)
  4877. payload = {
  4878. "roomId": canonical_room_id,
  4879. "interactionId": interaction_id,
  4880. "kind": kind,
  4881. "response": response_value,
  4882. }
  4883. request_hash = hashlib.sha256(
  4884. self._canonical_json(payload).encode()
  4885. ).hexdigest()
  4886. with self.write_transaction() as connection:
  4887. existing = connection.execute(
  4888. """SELECT operation, request_hash, response_json
  4889. FROM group_idempotency WHERE request_id = ?""",
  4890. (canonical_request_id,),
  4891. ).fetchone()
  4892. if existing is not None:
  4893. if (
  4894. existing["operation"] not in {operation, legacy_operation}
  4895. or existing["request_hash"] != request_hash
  4896. ):
  4897. raise IdempotencyConflict(
  4898. "requestId was already used for a different request"
  4899. )
  4900. state = self._idempotency_state(existing["response_json"])
  4901. if state["state"] == "claimed":
  4902. raise GroupConflictError(
  4903. "Interaction response is already in progress"
  4904. )
  4905. if state["state"] == "completed":
  4906. return {"state": "replay", "response": state["response"]}
  4907. if state["state"] == "failed":
  4908. return state
  4909. raise GroupStoreError("Stored interaction response is corrupt")
  4910. competing = connection.execute(
  4911. """SELECT operation, response_json FROM group_idempotency
  4912. WHERE operation IN (?, ?)""",
  4913. (operation, legacy_operation),
  4914. ).fetchall()
  4915. for candidate in competing:
  4916. state = self._idempotency_state(candidate["response_json"])
  4917. if (
  4918. state["state"] == "claimed"
  4919. and state["interactionId"] == interaction_id
  4920. ):
  4921. raise GroupConflictError("Interaction response is already claimed")
  4922. interaction = self._interaction_row(connection, interaction_id)
  4923. if interaction["room_id"] != canonical_room_id:
  4924. raise GroupNotFoundError("Interaction not found")
  4925. if interaction["kind"] != kind:
  4926. raise GroupConflictError("Interaction kind does not match")
  4927. if interaction["status"] != "pending":
  4928. raise GroupConflictError("Interaction is already resolved")
  4929. run = self._run_row(connection, interaction["run_id"])
  4930. self._active_room(connection, canonical_room_id)
  4931. self._enabled_agent(connection, canonical_room_id, run["agent_id"])
  4932. if run["status"] != "awaiting_input":
  4933. raise GroupConflictError("Interaction run is not awaiting input")
  4934. if run["runtime_session_id"] is None:
  4935. raise GroupConflictError("Interaction run has no runtime session")
  4936. first = connection.execute(
  4937. """SELECT id FROM group_interactions
  4938. WHERE run_id = ? AND kind = ? AND status = 'pending'
  4939. ORDER BY rowid ASC LIMIT 1""",
  4940. (run["id"], kind),
  4941. ).fetchone()
  4942. if first is None or first["id"] != interaction_id:
  4943. raise GroupConflictError(
  4944. "Interaction responses must preserve FIFO order"
  4945. )
  4946. sentinel = {
  4947. "state": "claimed",
  4948. "interactionId": interaction_id,
  4949. "kind": kind,
  4950. }
  4951. connection.execute(
  4952. """INSERT INTO group_idempotency
  4953. (request_id, operation, request_hash, response_json, created_at)
  4954. VALUES (?, ?, ?, ?, ?)""",
  4955. (
  4956. canonical_request_id,
  4957. operation,
  4958. request_hash,
  4959. self._canonical_json(sentinel),
  4960. self._now(),
  4961. ),
  4962. )
  4963. return {
  4964. "state": "claimed",
  4965. "interaction": self._interaction_wire(interaction),
  4966. "run": self._run_wire(run),
  4967. }
  4968. def finish_interaction_response(
  4969. self,
  4970. request_id: str,
  4971. *,
  4972. response: Mapping[str, object],
  4973. interaction_status: str = "resolved",
  4974. ) -> dict[str, object]:
  4975. """Commit a known Gateway response and release the run when possible."""
  4976. if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
  4977. raise ValueError("interaction_status must be resolved or cancelled")
  4978. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  4979. response_json = self._json_object(response, "response")
  4980. public_response = self._load_json(response_json)
  4981. with self.write_transaction() as connection:
  4982. claim = connection.execute(
  4983. """SELECT operation, response_json FROM group_idempotency
  4984. WHERE request_id = ?""",
  4985. (canonical_request_id,),
  4986. ).fetchone()
  4987. operation = (
  4988. None
  4989. if claim is None
  4990. else self._interaction_response_operation(claim["operation"])
  4991. )
  4992. if claim is None or operation is None:
  4993. raise GroupNotFoundError("Interaction response claim not found")
  4994. state = self._idempotency_state(claim["response_json"])
  4995. if state["state"] == "claimed" and (
  4996. operation[0] != state["kind"]
  4997. or (operation[1] is not None and operation[1] != state["interactionId"])
  4998. ):
  4999. raise GroupStoreError("Stored interaction response is corrupt")
  5000. if state["state"] == "completed":
  5001. stored_status = state.get("interactionStatus", "resolved")
  5002. if stored_status != interaction_status:
  5003. raise GroupConflictError(
  5004. "Interaction response terminal status changed"
  5005. )
  5006. return state["response"]
  5007. if state["state"] != "claimed":
  5008. raise GroupConflictError("Interaction response claim is terminal")
  5009. interaction = self._interaction_row(connection, state["interactionId"])
  5010. if interaction["status"] != "pending":
  5011. raise GroupConflictError("Interaction is already resolved")
  5012. run = self._run_row(connection, interaction["run_id"])
  5013. self._active_room(connection, run["room_id"])
  5014. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  5015. if run["status"] != "awaiting_input":
  5016. raise GroupConflictError("Interaction run is not awaiting input")
  5017. now = self._now()
  5018. connection.execute(
  5019. """UPDATE group_interactions
  5020. SET status = ?, resolved_at = ? WHERE id = ?""",
  5021. (interaction_status, now, interaction["id"]),
  5022. )
  5023. resolved = self._interaction_wire(
  5024. self._interaction_row(connection, interaction["id"])
  5025. )
  5026. self._append_event(
  5027. connection,
  5028. run["room_id"],
  5029. "interaction.resolved",
  5030. resolved,
  5031. created_at=now,
  5032. )
  5033. pending = connection.execute(
  5034. """SELECT 1 FROM group_interactions
  5035. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  5036. (run["id"],),
  5037. ).fetchone()
  5038. if pending is None:
  5039. response_row = self._message_row(connection, run["response_message_id"])
  5040. self._validate_run_message_status("running", response_row["status"])
  5041. changed = self._update_run(
  5042. connection, run, "running", now, UNSET, UNSET
  5043. )
  5044. self._append_event(
  5045. connection,
  5046. run["room_id"],
  5047. "run.updated",
  5048. changed,
  5049. created_at=now,
  5050. )
  5051. final = {
  5052. "state": "completed",
  5053. "interactionStatus": interaction_status,
  5054. "response": public_response,
  5055. }
  5056. connection.execute(
  5057. """UPDATE group_idempotency SET response_json = ?
  5058. WHERE request_id = ?""",
  5059. (self._canonical_json(final), canonical_request_id),
  5060. )
  5061. return public_response
  5062. def fail_interaction_response(
  5063. self, request_id: str, *, reason: str, uncertain: bool
  5064. ) -> dict[str, object]:
  5065. """Fail closed on an unknown Gateway outcome or release a retryable claim."""
  5066. canonical_request_id = self._canonical_uuid(request_id, "requestId")
  5067. failure_reason = self._message_text(
  5068. reason, "reason", max_bytes=4096, nonblank=True
  5069. )
  5070. if not isinstance(uncertain, bool):
  5071. raise ValueError("uncertain must be a boolean")
  5072. with self.write_transaction() as connection:
  5073. claim = connection.execute(
  5074. """SELECT operation, response_json FROM group_idempotency
  5075. WHERE request_id = ?""",
  5076. (canonical_request_id,),
  5077. ).fetchone()
  5078. operation = (
  5079. None
  5080. if claim is None
  5081. else self._interaction_response_operation(claim["operation"])
  5082. )
  5083. if claim is None or operation is None:
  5084. raise GroupNotFoundError("Interaction response claim not found")
  5085. state = self._idempotency_state(claim["response_json"])
  5086. if state["state"] == "claimed" and (
  5087. operation[0] != state["kind"]
  5088. or (operation[1] is not None and operation[1] != state["interactionId"])
  5089. ):
  5090. raise GroupStoreError("Stored interaction response is corrupt")
  5091. if state["state"] == "failed":
  5092. return state
  5093. if state["state"] != "claimed":
  5094. raise GroupConflictError("Interaction response claim is terminal")
  5095. interaction = self._interaction_row(connection, state["interactionId"])
  5096. run = self._run_row(connection, interaction["run_id"])
  5097. self._active_room(connection, run["room_id"])
  5098. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  5099. if run["status"] != "awaiting_input":
  5100. raise GroupConflictError("Interaction run is not awaiting input")
  5101. if not uncertain:
  5102. connection.execute(
  5103. "DELETE FROM group_idempotency WHERE request_id = ?",
  5104. (canonical_request_id,),
  5105. )
  5106. return {"state": "retryable"}
  5107. runtime_ids = (
  5108. [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
  5109. )
  5110. now = self._now()
  5111. self._cancel_pending_interactions(connection, run, now)
  5112. response_row = self._message_row(connection, run["response_message_id"])
  5113. changed = self._update_run(
  5114. connection, run, "failed", now, None, failure_reason
  5115. )
  5116. self._append_event(
  5117. connection,
  5118. run["room_id"],
  5119. "run.updated",
  5120. changed,
  5121. created_at=now,
  5122. )
  5123. if response_row["status"] != "completed":
  5124. connection.execute(
  5125. """UPDATE group_messages
  5126. SET status = 'failed', error = ?, updated_at = ? WHERE id = ?""",
  5127. (failure_reason, now, response_row["id"]),
  5128. )
  5129. message = self._message_wire(
  5130. self._message_row(connection, response_row["id"])
  5131. )
  5132. if message["visible"]:
  5133. self._append_event(
  5134. connection,
  5135. run["room_id"],
  5136. "message.upsert",
  5137. message,
  5138. created_at=now,
  5139. )
  5140. self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
  5141. final = {
  5142. "state": "failed",
  5143. "reason": failure_reason,
  5144. "runtimeSessionIds": runtime_ids,
  5145. "run": self._legacy_interaction_failure_run(changed),
  5146. }
  5147. self._fail_claimed_interaction_ledgers(
  5148. connection,
  5149. run_id=run["id"],
  5150. reason=failure_reason,
  5151. runtime_session_ids=runtime_ids,
  5152. run=changed,
  5153. )
  5154. connection.execute(
  5155. """UPDATE group_idempotency SET response_json = ?
  5156. WHERE request_id = ?""",
  5157. (self._canonical_json(final), canonical_request_id),
  5158. )
  5159. return final
  5160. def expire_interaction(self, interaction_id: str) -> dict[str, object]:
  5161. """Idempotently cancel a stale interaction and resume when it was last."""
  5162. interaction_id = self._interaction_id(interaction_id)
  5163. with self.write_transaction() as connection:
  5164. interaction = self._interaction_row(connection, interaction_id)
  5165. if interaction["status"] != "pending":
  5166. return self._interaction_wire(interaction)
  5167. run = self._run_row(connection, interaction["run_id"])
  5168. self._active_room(connection, run["room_id"])
  5169. self._enabled_agent(connection, run["room_id"], run["agent_id"])
  5170. now = self._now()
  5171. connection.execute(
  5172. """UPDATE group_interactions
  5173. SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
  5174. (now, interaction_id),
  5175. )
  5176. result = self._interaction_wire(
  5177. self._interaction_row(connection, interaction_id)
  5178. )
  5179. self._append_event(
  5180. connection,
  5181. run["room_id"],
  5182. "interaction.resolved",
  5183. result,
  5184. created_at=now,
  5185. )
  5186. remaining = connection.execute(
  5187. """SELECT 1 FROM group_interactions
  5188. WHERE run_id = ? AND status = 'pending' LIMIT 1""",
  5189. (run["id"],),
  5190. ).fetchone()
  5191. if run["status"] == "awaiting_input" and remaining is None:
  5192. response = self._message_row(connection, run["response_message_id"])
  5193. self._validate_run_message_status("running", response["status"])
  5194. changed = self._update_run(
  5195. connection, run, "running", now, UNSET, UNSET
  5196. )
  5197. self._append_event(
  5198. connection,
  5199. run["room_id"],
  5200. "run.updated",
  5201. changed,
  5202. created_at=now,
  5203. )
  5204. run_result = changed
  5205. else:
  5206. run_result = self._run_wire(run)
  5207. self._fail_claimed_interaction_ledgers(
  5208. connection,
  5209. run_id=run["id"],
  5210. interaction_id=interaction_id,
  5211. reason="Interaction expired",
  5212. runtime_session_ids=(
  5213. []
  5214. if run["runtime_session_id"] is None
  5215. else [run["runtime_session_id"]]
  5216. ),
  5217. run=run_result,
  5218. )
  5219. return result
  5220. def events_after(
  5221. self, cursor: int, limit: int = MAX_EVENT_BATCH_SIZE
  5222. ) -> list[dict[str, object]]:
  5223. cursor = self._nonnegative_int(cursor, "cursor")
  5224. self._page_limit(limit, MAX_EVENT_BATCH_SIZE, "limit")
  5225. with self.read_transaction() as connection:
  5226. current_epoch = self._validated_epoch(
  5227. self._metadata_value_from_connection(connection, "journal_epoch")
  5228. )
  5229. rows = connection.execute(
  5230. "SELECT * FROM group_events WHERE cursor > ? ORDER BY cursor ASC LIMIT ?",
  5231. (cursor, limit),
  5232. ).fetchall()
  5233. return [self._event_wire(row, current_epoch) for row in rows]
  5234. def cursor_status(self, epoch: str, cursor: int) -> str:
  5235. canonical_epoch = self._canonical_uuid(epoch, "epoch")
  5236. cursor = self._nonnegative_int(cursor, "cursor")
  5237. with self.read_transaction() as connection:
  5238. if canonical_epoch != self._validated_epoch(
  5239. self._metadata_value_from_connection(connection, "journal_epoch")
  5240. ):
  5241. return "epoch_mismatch"
  5242. bounds = connection.execute(
  5243. "SELECT MIN(cursor) AS oldest, MAX(cursor) AS latest FROM group_events"
  5244. ).fetchone()
  5245. latest = int(bounds["latest"] or 0)
  5246. if cursor > latest:
  5247. return "cursor_expired"
  5248. oldest = bounds["oldest"]
  5249. if oldest is not None and cursor < int(oldest) - 1:
  5250. return "cursor_expired"
  5251. return "ok"
  5252. def prune_events(self, now: float | None = None) -> int:
  5253. prune_now = self._now() if now is None else self._finite_timestamp(now, "now")
  5254. with self.write_transaction() as connection:
  5255. threshold = connection.execute(
  5256. "SELECT cursor FROM group_events ORDER BY cursor DESC LIMIT 1 OFFSET ?",
  5257. (MIN_RETAINED_EVENTS - 1,),
  5258. ).fetchone()
  5259. if threshold is None:
  5260. return 0
  5261. result = connection.execute(
  5262. "DELETE FROM group_events WHERE created_at < ? AND cursor < ?",
  5263. (prune_now - EVENT_RETENTION_SECONDS, threshold["cursor"]),
  5264. )
  5265. return result.rowcount
  5266. def _interrupt_runs_for_scope(
  5267. self,
  5268. connection: sqlite3.Connection,
  5269. *,
  5270. room_id: str,
  5271. reason: str,
  5272. now: float,
  5273. agent_id: str | None = None,
  5274. topic_id: str | None = None,
  5275. include_queued: bool = True,
  5276. ) -> dict[str, list[str]]:
  5277. statuses = (
  5278. "('queued', 'running', 'awaiting_input')"
  5279. if include_queued
  5280. else "('running', 'awaiting_input')"
  5281. )
  5282. query = f"""SELECT run.* FROM group_agent_runs AS run
  5283. JOIN group_messages AS response
  5284. ON response.id = run.response_message_id
  5285. WHERE run.room_id = ? AND run.status IN {statuses}"""
  5286. params: list[object] = [room_id]
  5287. if agent_id is not None:
  5288. query += " AND run.agent_id = ?"
  5289. params.append(agent_id)
  5290. if topic_id is not None:
  5291. query += " AND run.topic_id = ?"
  5292. params.append(topic_id)
  5293. query += " ORDER BY response.seq ASC, run.id ASC"
  5294. runs = connection.execute(query, params).fetchall()
  5295. changed_ids: list[str] = []
  5296. runtime_ids: list[str] = []
  5297. for run in runs:
  5298. run_runtime_ids = (
  5299. [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
  5300. )
  5301. if (
  5302. run["runtime_session_id"] is not None
  5303. and run["runtime_session_id"] not in runtime_ids
  5304. ):
  5305. runtime_ids.append(run["runtime_session_id"])
  5306. response = self._message_row(connection, run["response_message_id"])
  5307. if (
  5308. response["room_id"] != run["room_id"]
  5309. or response["sender_id"] != run["agent_id"]
  5310. ):
  5311. raise GroupStoreError("Run response message is corrupt")
  5312. self._validate_run_message_state(run, response)
  5313. changed = self._update_run(
  5314. connection, run, "interrupted", now, None, reason
  5315. )
  5316. self._append_event(
  5317. connection, room_id, "run.updated", changed, created_at=now
  5318. )
  5319. if response["status"] == "completed":
  5320. self._validate_run_message_status(changed["status"], response["status"])
  5321. else:
  5322. connection.execute(
  5323. """UPDATE group_messages
  5324. SET status = 'interrupted', error = ?, updated_at = ? WHERE id = ?""",
  5325. (reason, now, run["response_message_id"]),
  5326. )
  5327. message = self._message_wire(
  5328. self._message_row(connection, run["response_message_id"])
  5329. )
  5330. self._validate_run_message_status(changed["status"], message["status"])
  5331. if message["visible"]:
  5332. self._append_event(
  5333. connection,
  5334. room_id,
  5335. "message.upsert",
  5336. message,
  5337. created_at=now,
  5338. )
  5339. self._cancel_pending_interactions(
  5340. connection, run, now, order_by_created_at=True
  5341. )
  5342. self._fail_claimed_interaction_ledgers(
  5343. connection,
  5344. run_id=run["id"],
  5345. reason=reason,
  5346. runtime_session_ids=run_runtime_ids,
  5347. run=changed,
  5348. )
  5349. self._record_host_flow_terminal_plan_if_needed(
  5350. connection, self._run_row(connection, run["id"]), now
  5351. )
  5352. changed_ids.append(run["id"])
  5353. return {"runIds": changed_ids, "runtimeSessionIds": runtime_ids}
  5354. def recover_after_restart(self) -> list[str]:
  5355. with self.write_transaction() as connection:
  5356. runs = connection.execute(
  5357. "SELECT * FROM group_agent_runs WHERE status IN ('running', 'awaiting_input') ORDER BY created_at ASC, id ASC"
  5358. ).fetchall()
  5359. if not runs:
  5360. return []
  5361. now = self._now()
  5362. changed_ids: list[str] = []
  5363. for run in runs:
  5364. runtime_ids = (
  5365. []
  5366. if run["runtime_session_id"] is None
  5367. else [run["runtime_session_id"]]
  5368. )
  5369. response = self._message_row(connection, run["response_message_id"])
  5370. if (
  5371. response["room_id"] != run["room_id"]
  5372. or response["sender_id"] != run["agent_id"]
  5373. ):
  5374. raise GroupStoreError("Run response message is corrupt")
  5375. self._validate_run_message_state(run, response)
  5376. changed = self._update_run(
  5377. connection, run, "interrupted", now, None, "Dashboard restarted"
  5378. )
  5379. self._append_event(
  5380. connection, run["room_id"], "run.updated", changed, created_at=now
  5381. )
  5382. if response["status"] == "completed":
  5383. self._validate_run_message_status(
  5384. changed["status"], response["status"]
  5385. )
  5386. else:
  5387. connection.execute(
  5388. """UPDATE group_messages
  5389. SET status = 'interrupted', error = 'Dashboard restarted',
  5390. updated_at = ? WHERE id = ?""",
  5391. (now, run["response_message_id"]),
  5392. )
  5393. message = self._message_wire(
  5394. self._message_row(connection, run["response_message_id"])
  5395. )
  5396. self._validate_run_message_status(
  5397. changed["status"], message["status"]
  5398. )
  5399. if message["visible"]:
  5400. self._append_event(
  5401. connection,
  5402. run["room_id"],
  5403. "message.upsert",
  5404. message,
  5405. created_at=now,
  5406. )
  5407. self._cancel_pending_interactions(
  5408. connection, run, now, order_by_created_at=True
  5409. )
  5410. self._fail_claimed_interaction_ledgers(
  5411. connection,
  5412. run_id=run["id"],
  5413. reason="Dashboard restarted",
  5414. runtime_session_ids=runtime_ids,
  5415. run=changed,
  5416. )
  5417. self._record_host_flow_terminal_plan_if_needed(
  5418. connection, self._run_row(connection, run["id"]), now
  5419. )
  5420. changed_ids.append(run["id"])
  5421. return changed_ids
  5422. def _cancel_pending_interactions(
  5423. self,
  5424. connection: sqlite3.Connection,
  5425. run: sqlite3.Row,
  5426. now: float,
  5427. *,
  5428. order_by_created_at: bool = False,
  5429. ) -> list[dict[str, object]]:
  5430. """Cancel a run's pending cards and publish their durable resolutions."""
  5431. ordering = "created_at ASC, id ASC" if order_by_created_at else "rowid ASC"
  5432. interactions = connection.execute(
  5433. f"""SELECT id FROM group_interactions
  5434. WHERE run_id = ? AND status = 'pending' ORDER BY {ordering}""",
  5435. (run["id"],),
  5436. ).fetchall()
  5437. cancelled: list[dict[str, object]] = []
  5438. for interaction in interactions:
  5439. connection.execute(
  5440. """UPDATE group_interactions
  5441. SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
  5442. (now, interaction["id"]),
  5443. )
  5444. resolved = self._interaction_wire(
  5445. self._interaction_row(connection, interaction["id"])
  5446. )
  5447. self._append_event(
  5448. connection,
  5449. run["room_id"],
  5450. "interaction.resolved",
  5451. resolved,
  5452. created_at=now,
  5453. )
  5454. cancelled.append(resolved)
  5455. return cancelled
  5456. def _fail_claimed_interaction_ledgers(
  5457. self,
  5458. connection: sqlite3.Connection,
  5459. *,
  5460. run_id: str,
  5461. reason: str,
  5462. runtime_session_ids: list[str],
  5463. run: Mapping[str, object],
  5464. interaction_id: str | None = None,
  5465. ) -> None:
  5466. interactions = connection.execute(
  5467. """SELECT id, kind FROM group_interactions
  5468. WHERE run_id = ? ORDER BY rowid ASC""",
  5469. (run_id,),
  5470. ).fetchall()
  5471. if interaction_id is not None:
  5472. interactions = [
  5473. item for item in interactions if item["id"] == interaction_id
  5474. ]
  5475. if not interactions:
  5476. return
  5477. target_ids = {item["id"] for item in interactions}
  5478. scoped_operations = [
  5479. self._interaction_operation(item["kind"], item["id"])
  5480. for item in interactions
  5481. ]
  5482. placeholders = ", ".join("?" for _ in scoped_operations)
  5483. ledgers = connection.execute(
  5484. f"""SELECT request_id, operation, response_json
  5485. FROM group_idempotency WHERE operation IN ({placeholders})""",
  5486. scoped_operations,
  5487. ).fetchall()
  5488. legacy = connection.execute(
  5489. """SELECT request_id, operation, response_json
  5490. FROM group_idempotency WHERE operation IN (
  5491. 'interaction.approval.response',
  5492. 'interaction.clarification.response'
  5493. )"""
  5494. ).fetchall()
  5495. seen: set[str] = set()
  5496. terminal = {
  5497. "state": "failed",
  5498. "reason": reason,
  5499. "runtimeSessionIds": list(runtime_session_ids),
  5500. "run": self._legacy_interaction_failure_run(run),
  5501. }
  5502. encoded = self._canonical_json(terminal)
  5503. for ledger in (*ledgers, *legacy):
  5504. if ledger["request_id"] in seen:
  5505. continue
  5506. seen.add(ledger["request_id"])
  5507. operation = self._interaction_response_operation(ledger["operation"])
  5508. state = self._idempotency_state(ledger["response_json"])
  5509. if operation is None or state["state"] != "claimed":
  5510. continue
  5511. claimed_id = state["interactionId"]
  5512. if claimed_id not in target_ids:
  5513. continue
  5514. if operation[0] != state["kind"] or (
  5515. operation[1] is not None and operation[1] != claimed_id
  5516. ):
  5517. raise GroupStoreError("Stored interaction response is corrupt")
  5518. connection.execute(
  5519. """UPDATE group_idempotency SET response_json = ?
  5520. WHERE request_id = ?""",
  5521. (encoded, ledger["request_id"]),
  5522. )
  5523. def queued_run_count(self) -> int:
  5524. with self.connection() as connection:
  5525. return int(
  5526. connection.execute(
  5527. "SELECT COUNT(*) FROM group_agent_runs WHERE status = 'queued'"
  5528. ).fetchone()[0]
  5529. )
  5530. def list_pending_interactions(self, room_id: str) -> list[dict[str, object]]:
  5531. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  5532. with self.read_transaction() as connection:
  5533. self._room_detail(connection, canonical_room_id, include_archived=True)
  5534. rows = connection.execute(
  5535. "SELECT * FROM group_interactions WHERE room_id = ? AND status = 'pending' ORDER BY created_at, id",
  5536. (canonical_room_id,),
  5537. ).fetchall()
  5538. return [self._interaction_wire(row) for row in rows]
  5539. def list_queued_runs(self, room_id: str) -> list[dict[str, object]]:
  5540. canonical_room_id = self._canonical_uuid(room_id, "roomId")
  5541. with self.read_transaction() as connection:
  5542. self._room_detail(connection, canonical_room_id, include_archived=True)
  5543. rows = connection.execute(
  5544. "SELECT * FROM group_agent_runs WHERE room_id = ? AND status = 'queued' ORDER BY created_at, id",
  5545. (canonical_room_id,),
  5546. ).fetchall()
  5547. return [self._run_wire(row) for row in rows]
  5548. def latest_cursor(self) -> int:
  5549. with self.connection() as connection:
  5550. row = connection.execute(
  5551. "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
  5552. ).fetchone()
  5553. return int(row["cursor"])
  5554. @staticmethod
  5555. def _safe_context_seq(
  5556. connection: sqlite3.Connection,
  5557. room_id: str,
  5558. topic_id: str,
  5559. after_seq: int,
  5560. trigger_seq: int,
  5561. ) -> int:
  5562. hole = connection.execute(
  5563. """SELECT MIN(seq) AS seq FROM group_messages
  5564. WHERE room_id = ? AND topic_id = ? AND seq > ? AND seq <= ?
  5565. AND status NOT IN ('completed', 'failed', 'interrupted')""",
  5566. (room_id, topic_id, after_seq, trigger_seq),
  5567. ).fetchone()["seq"]
  5568. if hole is None:
  5569. return max(after_seq, trigger_seq)
  5570. return max(after_seq, int(hole) - 1)
  5571. def _append_agent_status(
  5572. self,
  5573. connection: sqlite3.Connection,
  5574. room_id: str,
  5575. agent_id: str,
  5576. now: float,
  5577. ) -> None:
  5578. row = connection.execute(
  5579. """SELECT id, status FROM group_agent_runs
  5580. WHERE room_id = ? AND agent_id = ?
  5581. AND status IN ('queued', 'running', 'awaiting_input')
  5582. ORDER BY CASE status
  5583. WHEN 'awaiting_input' THEN 3
  5584. WHEN 'running' THEN 2
  5585. ELSE 1 END DESC,
  5586. created_at ASC, id ASC
  5587. LIMIT 1""",
  5588. (room_id, agent_id),
  5589. ).fetchone()
  5590. payload: dict[str, object] = {
  5591. "roomId": room_id,
  5592. "agentId": agent_id,
  5593. "status": "idle" if row is None else row["status"],
  5594. "runId": None if row is None else row["id"],
  5595. }
  5596. self._append_event(connection, room_id, "agent.status", payload, created_at=now)
  5597. def _append_event(
  5598. self,
  5599. connection: sqlite3.Connection,
  5600. room_id: str,
  5601. event_type: str,
  5602. payload: Mapping[str, object],
  5603. *,
  5604. created_at: float | None = None,
  5605. ) -> int:
  5606. epoch = self._metadata_value_from_connection(connection, "journal_epoch")
  5607. event_time = self._now() if created_at is None else created_at
  5608. cursor = connection.execute(
  5609. """INSERT INTO group_events(epoch, room_id, event_type, payload_json, created_at)
  5610. VALUES (?, ?, ?, ?, ?) RETURNING cursor""",
  5611. (
  5612. epoch,
  5613. room_id,
  5614. event_type,
  5615. self._canonical_json(payload),
  5616. event_time,
  5617. ),
  5618. ).fetchone()["cursor"]
  5619. if event_type == "message.upsert":
  5620. topic_id = payload.get("topicId")
  5621. if not isinstance(topic_id, str):
  5622. raise GroupStoreError("Message event topic identity is missing")
  5623. connection.execute(
  5624. """UPDATE group_topics
  5625. SET updated_at = CASE WHEN updated_at < ? THEN ? ELSE updated_at END
  5626. WHERE id = ? AND room_id = ?""",
  5627. (event_time, event_time, topic_id, room_id),
  5628. )
  5629. topic = self._topic_summary_by_id(connection, room_id, topic_id)
  5630. connection.execute(
  5631. """INSERT INTO group_events
  5632. (epoch, room_id, event_type, payload_json, created_at)
  5633. VALUES (?, ?, 'topic.updated', ?, ?)""",
  5634. (epoch, room_id, self._canonical_json(topic), event_time),
  5635. )
  5636. message_activity = (
  5637. event_type == "message.upsert"
  5638. and payload.get("status") in {"completed", "failed", "interrupted"}
  5639. )
  5640. if event_type == "run.updated" or message_activity:
  5641. activity = self._room_activity_from_connection(connection, room_id)
  5642. connection.execute(
  5643. """INSERT INTO group_events
  5644. (epoch, room_id, event_type, payload_json, created_at)
  5645. VALUES (?, ?, 'room.activity', ?, ?)""",
  5646. (epoch, room_id, self._canonical_json(activity), event_time),
  5647. )
  5648. return int(cursor)
  5649. def _append_room_updated_summary(
  5650. self,
  5651. connection: sqlite3.Connection,
  5652. room_id: str,
  5653. *,
  5654. created_at: float,
  5655. ) -> None:
  5656. room = connection.execute(
  5657. """SELECT id, name, cwd, instructions, max_reply_rounds, orchestration_mode,
  5658. created_at, updated_at, archived,
  5659. (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id)
  5660. AS agent_count,
  5661. (SELECT COUNT(*) FROM group_topics WHERE room_id = group_rooms.id)
  5662. AS topic_count
  5663. FROM group_rooms WHERE id = ? AND archived = 0""",
  5664. (room_id,),
  5665. ).fetchone()
  5666. if room is None:
  5667. raise GroupNotFoundError("Room not found")
  5668. self._append_event(
  5669. connection,
  5670. room_id,
  5671. "room.updated",
  5672. self._room_summary(room),
  5673. created_at=created_at,
  5674. )
  5675. def _room_detail(
  5676. self, connection: sqlite3.Connection, room_id: str, *, include_archived: bool
  5677. ) -> dict[str, object]:
  5678. room = connection.execute(
  5679. "SELECT * FROM group_rooms WHERE id = ?", (room_id,)
  5680. ).fetchone()
  5681. if room is None or (room["archived"] and not include_archived):
  5682. raise GroupNotFoundError("Room not found")
  5683. agents = connection.execute(
  5684. "SELECT * FROM group_agents WHERE room_id = ? ORDER BY created_at ASC, id ASC",
  5685. (room_id,),
  5686. ).fetchall()
  5687. result = self._room_wire(room)
  5688. result["agents"] = [self._agent_wire(agent) for agent in agents]
  5689. return result
  5690. def prepare_run_session_configuration(
  5691. self, run_id: str, configuration: Mapping[str, object]
  5692. ) -> bool:
  5693. """Detach a stale stored session before this claimed run is bound.
  5694. Configuration changes never interrupt the currently bound run. A later
  5695. claimed run reaches this method only after agent serialization, so it
  5696. can safely rotate the dormant stored session and rebuild full context.
  5697. """
  5698. canonical_run_id = self._canonical_uuid(run_id, "runId")
  5699. normalized = {
  5700. "model": configuration.get("model"),
  5701. "provider": configuration.get("provider"),
  5702. "reasoning_effort": configuration.get("reasoning_effort"),
  5703. "fast": configuration.get("fast"),
  5704. }
  5705. serialized = self._canonical_json(normalized)
  5706. with self.write_transaction() as connection:
  5707. run = self._run_row(connection, canonical_run_id)
  5708. if run["status"] != "running" or run["runtime_session_id"] is not None:
  5709. raise GroupConflictError("Run does not accept configuration rotation")
  5710. agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
  5711. if agent["session_config_json"] == serialized:
  5712. return False
  5713. now = self._now()
  5714. connection.execute(
  5715. """UPDATE group_agents
  5716. SET stored_session_id = NULL,
  5717. last_context_message_seq = 0,
  5718. session_config_json = ?,
  5719. updated_at = ?
  5720. WHERE id = ? AND room_id = ?""",
  5721. (serialized, now, agent["id"], run["room_id"]),
  5722. )
  5723. connection.execute(
  5724. """UPDATE group_agent_topic_state
  5725. SET last_context_message_seq = 0, updated_at = ?
  5726. WHERE agent_id = ?""",
  5727. (now, agent["id"]),
  5728. )
  5729. refreshed = self._owned_agent(connection, run["room_id"], run["agent_id"])
  5730. self._append_event(
  5731. connection,
  5732. run["room_id"],
  5733. "agent.updated",
  5734. self._agent_wire(refreshed),
  5735. created_at=now,
  5736. )
  5737. return True
  5738. @staticmethod
  5739. def _compatibility_topic_id(room_id: str) -> str:
  5740. return str(
  5741. uuid.uuid5(
  5742. uuid.NAMESPACE_URL,
  5743. f"hermes://yaoyao-group/{room_id}/compatibility-topic",
  5744. )
  5745. )
  5746. @staticmethod
  5747. def _topic_title(content: str) -> str:
  5748. normalized = " ".join(content.split()).strip()
  5749. return (normalized or "话题")[:_TOPIC_TITLE_LENGTH]
  5750. @staticmethod
  5751. def _topic_row(
  5752. connection: sqlite3.Connection, room_id: str, topic_id: str
  5753. ) -> sqlite3.Row:
  5754. topic = connection.execute(
  5755. "SELECT * FROM group_topics WHERE id = ? AND room_id = ?",
  5756. (topic_id, room_id),
  5757. ).fetchone()
  5758. if topic is None:
  5759. raise GroupNotFoundError("Topic not found in room")
  5760. return topic
  5761. def _active_topic(
  5762. self, connection: sqlite3.Connection, room_id: str, topic_id: str
  5763. ) -> sqlite3.Row:
  5764. topic = self._topic_row(connection, room_id, topic_id)
  5765. if topic["archived"]:
  5766. raise GroupNotFoundError("Topic not found in room")
  5767. return topic
  5768. @classmethod
  5769. def _topic_summary_by_id(
  5770. cls, connection: sqlite3.Connection, room_id: str, topic_id: str
  5771. ) -> dict[str, object]:
  5772. row = connection.execute(
  5773. """SELECT topic.*,
  5774. (SELECT COUNT(*) FROM group_messages AS counted
  5775. WHERE counted.topic_id = topic.id AND counted.visible = 1)
  5776. AS message_count,
  5777. COALESCE((SELECT CASE WHEN TRIM(latest.content) != ''
  5778. THEN latest.content ELSE latest.error END
  5779. FROM group_messages AS latest
  5780. WHERE latest.topic_id = topic.id AND latest.visible = 1
  5781. AND (TRIM(latest.content) != '' OR TRIM(latest.error) != '')
  5782. ORDER BY latest.seq DESC LIMIT 1), '') AS preview,
  5783. (SELECT COUNT(*) FROM group_messages AS unread
  5784. WHERE unread.topic_id = topic.id AND unread.visible = 1
  5785. AND unread.sender_kind = 'agent'
  5786. AND (TRIM(unread.content) != '' OR TRIM(unread.error) != '')
  5787. AND unread.seq > topic.last_read_message_seq) AS unread_count,
  5788. COALESCE((SELECT MAX(visible_message.seq)
  5789. FROM group_messages AS visible_message
  5790. WHERE visible_message.topic_id = topic.id
  5791. AND visible_message.visible = 1), 0) AS latest_message_seq
  5792. FROM group_topics AS topic
  5793. WHERE topic.id = ? AND topic.room_id = ?""",
  5794. (topic_id, room_id),
  5795. ).fetchone()
  5796. if row is None:
  5797. raise GroupNotFoundError("Topic not found in room")
  5798. return cls._topic_summary(row)
  5799. def _ensure_topic(
  5800. self,
  5801. connection: sqlite3.Connection,
  5802. room_id: str,
  5803. topic_id: str,
  5804. title_source: str,
  5805. now: float,
  5806. ) -> sqlite3.Row:
  5807. existing = connection.execute(
  5808. "SELECT * FROM group_topics WHERE id = ?", (topic_id,)
  5809. ).fetchone()
  5810. if existing is not None:
  5811. if existing["room_id"] != room_id:
  5812. raise GroupConflictError("Topic does not belong to room")
  5813. if existing["archived"]:
  5814. raise GroupConflictError("Topic is archived")
  5815. return existing
  5816. connection.execute(
  5817. """INSERT INTO group_topics
  5818. (id, room_id, title, created_at, updated_at)
  5819. VALUES (?, ?, ?, ?, ?)""",
  5820. (topic_id, room_id, self._topic_title(title_source), now, now),
  5821. )
  5822. connection.execute(
  5823. """INSERT INTO group_agent_topic_state
  5824. (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
  5825. SELECT id, ?, 0, ?, ? FROM group_agents WHERE room_id = ?""",
  5826. (topic_id, now, now, room_id),
  5827. )
  5828. return self._topic_row(connection, room_id, topic_id)
  5829. @staticmethod
  5830. def _agent_topic_state(
  5831. connection: sqlite3.Connection, agent_id: str, topic_id: str
  5832. ) -> sqlite3.Row:
  5833. state = connection.execute(
  5834. """SELECT * FROM group_agent_topic_state
  5835. WHERE agent_id = ? AND topic_id = ?""",
  5836. (agent_id, topic_id),
  5837. ).fetchone()
  5838. if state is None:
  5839. raise GroupStoreError("Agent topic context state is missing")
  5840. return state
  5841. def _active_room(self, connection: sqlite3.Connection, room_id: str) -> sqlite3.Row:
  5842. room = connection.execute(
  5843. "SELECT * FROM group_rooms WHERE id = ? AND archived = 0", (room_id,)
  5844. ).fetchone()
  5845. if room is None:
  5846. raise GroupNotFoundError("Room not found")
  5847. return room
  5848. def _owned_agent(
  5849. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  5850. ) -> sqlite3.Row:
  5851. agent = connection.execute(
  5852. "SELECT * FROM group_agents WHERE id = ? AND room_id = ?",
  5853. (agent_id, room_id),
  5854. ).fetchone()
  5855. if agent is None:
  5856. raise GroupNotFoundError("Agent not found in room")
  5857. return agent
  5858. @staticmethod
  5859. def _room_host(
  5860. connection: sqlite3.Connection, room_id: str
  5861. ) -> sqlite3.Row:
  5862. host = connection.execute(
  5863. "SELECT * FROM group_agents WHERE room_id = ? AND is_host = 1",
  5864. (room_id,),
  5865. ).fetchone()
  5866. if host is None:
  5867. raise GroupStoreError("Room host is missing")
  5868. return host
  5869. @staticmethod
  5870. def _first_enabled_host_candidate(
  5871. connection: sqlite3.Connection,
  5872. room_id: str,
  5873. *,
  5874. exclude_agent_id: str,
  5875. ) -> sqlite3.Row | None:
  5876. return connection.execute(
  5877. """SELECT * FROM group_agents
  5878. WHERE room_id = ? AND enabled = 1 AND id != ?
  5879. ORDER BY created_at ASC, id ASC LIMIT 1""",
  5880. (room_id, exclude_agent_id),
  5881. ).fetchone()
  5882. def _switch_host(
  5883. self,
  5884. connection: sqlite3.Connection,
  5885. room_id: str,
  5886. agent_id: str,
  5887. *,
  5888. now: float,
  5889. ) -> tuple[dict[str, object], dict[str, object]] | None:
  5890. current = self._room_host(connection, room_id)
  5891. if current["id"] == agent_id:
  5892. return None
  5893. replacement = self._owned_agent(connection, room_id, agent_id)
  5894. if not replacement["enabled"]:
  5895. raise GroupConflictError("Host Agent must be enabled")
  5896. connection.execute(
  5897. """UPDATE group_agents SET is_host = 0, updated_at = ?
  5898. WHERE id = ? AND room_id = ?""",
  5899. (now, current["id"], room_id),
  5900. )
  5901. connection.execute(
  5902. """UPDATE group_agents SET is_host = 1, updated_at = ?
  5903. WHERE id = ? AND room_id = ?""",
  5904. (now, replacement["id"], room_id),
  5905. )
  5906. return (
  5907. self._agent_detail(connection, room_id, str(current["id"])),
  5908. self._agent_detail(connection, room_id, str(replacement["id"])),
  5909. )
  5910. def _enabled_agent(
  5911. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  5912. ) -> sqlite3.Row:
  5913. agent = self._owned_agent(connection, room_id, agent_id)
  5914. if not agent["enabled"]:
  5915. raise GroupConflictError("Agent is disabled")
  5916. return agent
  5917. @staticmethod
  5918. def _require_available_runtime(
  5919. connection: sqlite3.Connection, runtime_session_id: str, run_id: str
  5920. ) -> None:
  5921. occupied = connection.execute(
  5922. """SELECT id FROM group_agent_runs
  5923. WHERE runtime_session_id = ?
  5924. AND status IN ('running', 'awaiting_input')
  5925. AND id != ? LIMIT 1""",
  5926. (runtime_session_id, run_id),
  5927. ).fetchone()
  5928. if occupied is not None:
  5929. raise GroupConflictError("Runtime session is already in use")
  5930. def _agent_detail(
  5931. self, connection: sqlite3.Connection, room_id: str, agent_id: str
  5932. ) -> dict[str, object]:
  5933. return self._agent_wire(self._owned_agent(connection, room_id, agent_id))
  5934. @staticmethod
  5935. def _message_row(connection: sqlite3.Connection, message_id: str) -> sqlite3.Row:
  5936. row = connection.execute(
  5937. "SELECT * FROM group_messages WHERE id = ?", (message_id,)
  5938. ).fetchone()
  5939. if row is None:
  5940. raise GroupNotFoundError("Message not found")
  5941. return row
  5942. @staticmethod
  5943. def _message_with_execution_row(
  5944. connection: sqlite3.Connection, message_id: str
  5945. ) -> sqlite3.Row:
  5946. row = connection.execute(
  5947. """SELECT message.*,
  5948. run.requested_model AS execution_requested_model,
  5949. run.requested_provider AS execution_requested_provider,
  5950. run.requested_reasoning_effort AS execution_requested_reasoning_effort,
  5951. run.requested_fast_mode AS execution_requested_fast_mode,
  5952. run.actual_model AS execution_actual_model,
  5953. run.actual_provider AS execution_actual_provider,
  5954. run.actual_reasoning_effort AS execution_actual_reasoning_effort,
  5955. run.actual_fast_mode AS execution_actual_fast_mode
  5956. FROM group_messages AS message
  5957. LEFT JOIN group_agent_runs AS run
  5958. ON run.response_message_id = message.id
  5959. WHERE message.id = ?""",
  5960. (message_id,),
  5961. ).fetchone()
  5962. if row is None:
  5963. raise GroupNotFoundError("Message not found")
  5964. return row
  5965. @staticmethod
  5966. def _run_row(connection: sqlite3.Connection, run_id: str) -> sqlite3.Row:
  5967. row = connection.execute(
  5968. "SELECT * FROM group_agent_runs WHERE id = ?", (run_id,)
  5969. ).fetchone()
  5970. if row is None:
  5971. raise GroupNotFoundError("Run not found")
  5972. return row
  5973. @staticmethod
  5974. def _interaction_row(
  5975. connection: sqlite3.Connection, interaction_id: str
  5976. ) -> sqlite3.Row:
  5977. row = connection.execute(
  5978. "SELECT * FROM group_interactions WHERE id = ?", (interaction_id,)
  5979. ).fetchone()
  5980. if row is None:
  5981. raise GroupNotFoundError("Interaction not found")
  5982. return row
  5983. @classmethod
  5984. def _validate_run_message_state(
  5985. cls, run: sqlite3.Row, message: sqlite3.Row
  5986. ) -> None:
  5987. if (
  5988. run["room_id"] != message["room_id"]
  5989. or run["topic_id"] != message["topic_id"]
  5990. ):
  5991. raise GroupStoreError("Run response message is corrupt")
  5992. cls._validate_run_message_status(run["status"], message["status"])
  5993. @staticmethod
  5994. def _validate_run_message_status(run_status: str, message_status: str) -> None:
  5995. if message_status not in _MESSAGE_STATUSES_BY_RUN.get(run_status, frozenset()):
  5996. raise GroupConflictError("Run and response message states conflict")
  5997. def _update_run(
  5998. self,
  5999. connection: sqlite3.Connection,
  6000. run: sqlite3.Row,
  6001. status: str,
  6002. now: float,
  6003. runtime_session_id: object,
  6004. error: object,
  6005. ) -> dict[str, object]:
  6006. runtime = (
  6007. run["runtime_session_id"]
  6008. if runtime_session_id is UNSET
  6009. else runtime_session_id
  6010. )
  6011. run_error = run["error"] if error is UNSET else error
  6012. try:
  6013. connection.execute(
  6014. "UPDATE group_agent_runs SET status = ?, runtime_session_id = ?, error = ?, updated_at = ? WHERE id = ?",
  6015. (status, runtime, run_error, now, run["id"]),
  6016. )
  6017. except sqlite3.IntegrityError as conflict:
  6018. if "group_agent_runs.runtime_session_id" in str(conflict):
  6019. raise GroupConflictError(
  6020. "Runtime session is already in use"
  6021. ) from conflict
  6022. raise
  6023. return self._run_wire(self._run_row(connection, run["id"]))
  6024. @staticmethod
  6025. def _message_wire(row: sqlite3.Row) -> dict[str, object]:
  6026. try:
  6027. tool_state = GroupStore._load_json(row["tool_state_json"])
  6028. except (
  6029. TypeError,
  6030. ValueError,
  6031. UnicodeDecodeError,
  6032. json.JSONDecodeError,
  6033. ) as error:
  6034. raise GroupStoreError("Stored message tool state is corrupt") from error
  6035. if not isinstance(tool_state, list) or not all(
  6036. isinstance(item, dict) for item in tool_state
  6037. ):
  6038. raise GroupStoreError("Stored message tool state is corrupt")
  6039. result = {
  6040. "seq": row["seq"],
  6041. "id": row["id"],
  6042. "roomId": row["room_id"],
  6043. "topicId": row["topic_id"],
  6044. "senderKind": row["sender_kind"],
  6045. "senderId": row["sender_id"],
  6046. "senderName": row["sender_name"],
  6047. "rootMessageId": row["root_message_id"],
  6048. "replyToMessageId": row["reply_to_message_id"],
  6049. "clientMessageId": row["client_message_id"],
  6050. "content": row["content"],
  6051. "reasoning": row["reasoning"],
  6052. "toolState": tool_state,
  6053. "status": row["status"],
  6054. "error": row["error"],
  6055. "visible": bool(row["visible"]),
  6056. "createdAt": row["created_at"],
  6057. "updatedAt": row["updated_at"],
  6058. }
  6059. keys = set(row.keys())
  6060. if "execution_actual_model" in keys:
  6061. values = {
  6062. "requestedModel": row["execution_requested_model"],
  6063. "requestedProvider": row["execution_requested_provider"],
  6064. "requestedReasoningEffort": row[
  6065. "execution_requested_reasoning_effort"
  6066. ],
  6067. "requestedFastMode": (
  6068. None
  6069. if row["execution_requested_fast_mode"] is None
  6070. else bool(row["execution_requested_fast_mode"])
  6071. ),
  6072. "actualModel": row["execution_actual_model"],
  6073. "actualProvider": row["execution_actual_provider"],
  6074. "actualReasoningEffort": row["execution_actual_reasoning_effort"],
  6075. "actualFastMode": (
  6076. None
  6077. if row["execution_actual_fast_mode"] is None
  6078. else bool(row["execution_actual_fast_mode"])
  6079. ),
  6080. }
  6081. if any(value is not None for value in values.values()):
  6082. result["execution"] = values
  6083. return result
  6084. @classmethod
  6085. def _projection_message(cls, row: sqlite3.Row) -> dict[str, object]:
  6086. try:
  6087. tool_state = cls._load_json(row["tool_state_json"])
  6088. except (
  6089. TypeError,
  6090. ValueError,
  6091. UnicodeDecodeError,
  6092. json.JSONDecodeError,
  6093. ) as error:
  6094. raise GroupStoreError("Stored message tool state is corrupt") from error
  6095. if not isinstance(tool_state, list) or not all(
  6096. isinstance(item, dict) for item in tool_state
  6097. ):
  6098. raise GroupStoreError("Stored message tool state is corrupt")
  6099. tool_names: list[str] = []
  6100. tool_names_truncated = False
  6101. for item in tool_state:
  6102. name = None
  6103. for key in ("name", "toolName"):
  6104. candidate = item.get(key)
  6105. if not isinstance(candidate, str) or not candidate:
  6106. continue
  6107. if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,119}", candidate) is None:
  6108. tool_names_truncated = True
  6109. continue
  6110. name = candidate
  6111. break
  6112. if name is None or name in tool_names:
  6113. continue
  6114. if len(tool_names) >= 16:
  6115. tool_names_truncated = True
  6116. break
  6117. tool_names.append(name)
  6118. return {
  6119. "seq": int(row["seq"]),
  6120. "senderKind": row["sender_kind"],
  6121. "senderId": row["sender_id"],
  6122. "senderName": row["sender_name"],
  6123. "content": row["content"],
  6124. "reasoning": row["reasoning"],
  6125. "toolNames": tool_names,
  6126. "status": row["status"],
  6127. "summary": row["error"],
  6128. "truncated": tool_names_truncated,
  6129. }
  6130. @classmethod
  6131. def _bound_projection_messages(
  6132. cls,
  6133. messages: list[dict[str, object]],
  6134. *,
  6135. omitted_count: int,
  6136. omitted_through_seq: int | None,
  6137. ) -> tuple[list[dict[str, object]], int, int | None, dict[str, object] | None]:
  6138. while len(messages) > 1:
  6139. omitted_summary = cls._projection_omitted_summary(
  6140. omitted_count, omitted_through_seq
  6141. )
  6142. if (
  6143. cls._projection_size(messages, omitted_summary)
  6144. <= CONTEXT_CHARACTER_BUDGET
  6145. ):
  6146. break
  6147. removed = messages.pop(0)
  6148. omitted_count += 1
  6149. omitted_through_seq = int(removed["seq"])
  6150. omitted_summary = cls._projection_omitted_summary(
  6151. omitted_count, omitted_through_seq
  6152. )
  6153. if (
  6154. messages
  6155. and cls._projection_size(messages, omitted_summary)
  6156. > CONTEXT_CHARACTER_BUDGET
  6157. ):
  6158. cls._truncate_projection_message(messages[0], omitted_summary)
  6159. if cls._projection_size(messages, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
  6160. raise GroupStoreError("Projection metadata exceeds the character budget")
  6161. return messages, omitted_count, omitted_through_seq, omitted_summary
  6162. @staticmethod
  6163. def _projection_omitted_summary(
  6164. count: int, through_seq: int | None
  6165. ) -> dict[str, object] | None:
  6166. if count == 0:
  6167. return None
  6168. if through_seq is None:
  6169. raise GroupStoreError("Projection omission metadata is corrupt")
  6170. return {
  6171. "messageCount": count,
  6172. "throughSeq": through_seq,
  6173. "text": f"Omitted {count} earlier messages through seq {through_seq}.",
  6174. }
  6175. @classmethod
  6176. def _projection_size(
  6177. cls,
  6178. messages: list[dict[str, object]],
  6179. omitted_summary: dict[str, object] | None,
  6180. ) -> int:
  6181. return len(
  6182. cls._canonical_json(
  6183. {"messages": messages, "omittedSummary": omitted_summary}
  6184. ).encode("utf-8")
  6185. )
  6186. @classmethod
  6187. def _truncate_projection_message(
  6188. cls,
  6189. message: dict[str, object],
  6190. omitted_summary: dict[str, object] | None,
  6191. ) -> None:
  6192. marker = "…[truncated]"
  6193. originals = {
  6194. field: message[field]
  6195. for field in ("content", "reasoning", "summary")
  6196. if isinstance(message[field], str) and message[field]
  6197. }
  6198. message["truncated"] = True
  6199. for field in originals:
  6200. message[field] = marker
  6201. wrapper = [message]
  6202. if cls._projection_size(wrapper, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
  6203. raise GroupStoreError("Projection identity exceeds the character budget")
  6204. for field in ("content", "reasoning", "summary"):
  6205. original = originals.get(field)
  6206. if original is None:
  6207. continue
  6208. low = 0
  6209. high = len(original)
  6210. while low < high:
  6211. candidate = (low + high + 1) // 2
  6212. message[field] = (
  6213. original
  6214. if candidate == len(original)
  6215. else f"{original[:candidate]}{marker}"
  6216. )
  6217. if (
  6218. cls._projection_size(wrapper, omitted_summary)
  6219. <= CONTEXT_CHARACTER_BUDGET
  6220. ):
  6221. low = candidate
  6222. else:
  6223. high = candidate - 1
  6224. message[field] = (
  6225. original if low == len(original) else f"{original[:low]}{marker}"
  6226. )
  6227. @staticmethod
  6228. def _run_wire(row: sqlite3.Row) -> dict[str, object]:
  6229. return {
  6230. "id": row["id"],
  6231. "roomId": row["room_id"],
  6232. "topicId": row["topic_id"],
  6233. "agentId": row["agent_id"],
  6234. "triggerMessageId": row["trigger_message_id"],
  6235. "responseMessageId": row["response_message_id"],
  6236. "rootMessageId": row["root_message_id"],
  6237. "depth": row["depth"],
  6238. "replyMode": row["reply_mode"],
  6239. "status": row["status"],
  6240. "runtimeSessionId": row["runtime_session_id"],
  6241. "requestedModel": row["requested_model"],
  6242. "requestedProvider": row["requested_provider"],
  6243. "requestedReasoningEffort": row["requested_reasoning_effort"],
  6244. "requestedFastMode": (
  6245. None
  6246. if row["requested_fast_mode"] is None
  6247. else bool(row["requested_fast_mode"])
  6248. ),
  6249. "actualModel": row["actual_model"],
  6250. "actualProvider": row["actual_provider"],
  6251. "actualReasoningEffort": row["actual_reasoning_effort"],
  6252. "actualFastMode": (
  6253. None
  6254. if row["actual_fast_mode"] is None
  6255. else bool(row["actual_fast_mode"])
  6256. ),
  6257. "error": row["error"],
  6258. "createdAt": row["created_at"],
  6259. "updatedAt": row["updated_at"],
  6260. }
  6261. @staticmethod
  6262. def _legacy_interaction_failure_run(
  6263. run: Mapping[str, object],
  6264. ) -> dict[str, object]:
  6265. """Keep the pre-v4 strict HTTP replay shape for failed interactions."""
  6266. result = dict(run)
  6267. result.pop("topicId", None)
  6268. for field in (
  6269. "requestedModel",
  6270. "requestedProvider",
  6271. "requestedReasoningEffort",
  6272. "requestedFastMode",
  6273. "actualModel",
  6274. "actualProvider",
  6275. "actualReasoningEffort",
  6276. "actualFastMode",
  6277. ):
  6278. result.pop(field, None)
  6279. return result
  6280. @staticmethod
  6281. def _interaction_wire(row: sqlite3.Row) -> dict[str, object]:
  6282. try:
  6283. payload = GroupStore._load_json(row["payload_json"])
  6284. except (
  6285. TypeError,
  6286. ValueError,
  6287. UnicodeDecodeError,
  6288. json.JSONDecodeError,
  6289. ) as error:
  6290. raise GroupStoreError("Stored interaction payload is corrupt") from error
  6291. if not isinstance(payload, dict):
  6292. raise GroupStoreError("Stored interaction payload is corrupt")
  6293. return {
  6294. "id": row["id"],
  6295. "roomId": row["room_id"],
  6296. "topicId": row["topic_id"],
  6297. "agentId": row["agent_id"],
  6298. "runId": row["run_id"],
  6299. "kind": row["kind"],
  6300. "payload": payload,
  6301. "status": row["status"],
  6302. "createdAt": row["created_at"],
  6303. "resolvedAt": row["resolved_at"],
  6304. }
  6305. def _event_wire(self, row: sqlite3.Row, current_epoch: str) -> dict[str, object]:
  6306. try:
  6307. epoch = self._validated_epoch(row["epoch"])
  6308. payload = self._load_json(row["payload_json"])
  6309. except (
  6310. TypeError,
  6311. ValueError,
  6312. UnicodeDecodeError,
  6313. json.JSONDecodeError,
  6314. ) as error:
  6315. raise GroupStoreError("Stored event is corrupt") from error
  6316. if epoch != current_epoch or not isinstance(payload, dict):
  6317. raise GroupStoreError("Stored event is corrupt")
  6318. return {
  6319. "cursor": row["cursor"],
  6320. "epoch": epoch,
  6321. "roomId": row["room_id"],
  6322. "eventType": row["event_type"],
  6323. "payload": payload,
  6324. "createdAt": row["created_at"],
  6325. }
  6326. @staticmethod
  6327. def _message_text(
  6328. value: object, field: str, *, max_bytes: int, nonblank: bool = False
  6329. ) -> str:
  6330. if not isinstance(value, str):
  6331. raise ValueError(f"{field} must be a string")
  6332. try:
  6333. encoded = value.encode("utf-8")
  6334. except UnicodeEncodeError as error:
  6335. raise ValueError(f"{field} must be valid UTF-8") from error
  6336. if len(encoded) > max_bytes:
  6337. raise ValueError(f"{field} exceeds maximum size")
  6338. if nonblank and not value.strip():
  6339. raise ValueError(f"{field} must not be blank")
  6340. return value
  6341. @staticmethod
  6342. def _orchestration_mode(value: object) -> str:
  6343. if not isinstance(value, str) or value not in ORCHESTRATION_MODES:
  6344. raise ValueError("orchestrationMode must be free or host")
  6345. return value
  6346. @classmethod
  6347. def _mention_agent_ids(cls, value: object) -> list[str]:
  6348. if not isinstance(value, list):
  6349. raise ValueError("mentionAgentIds must be a list")
  6350. result = [
  6351. cls._canonical_uuid(agent_id, "mentionAgentIds") for agent_id in value
  6352. ]
  6353. if len(result) != len(set(result)):
  6354. raise GroupConflictError("mentionAgentIds must be unique")
  6355. return result
  6356. @staticmethod
  6357. def _interaction_id(value: object) -> str:
  6358. return normalize_interaction_id(value)
  6359. @staticmethod
  6360. def _runtime_session_id(value: object) -> str | None:
  6361. if value is None:
  6362. return None
  6363. if (
  6364. not isinstance(value, str)
  6365. or not value
  6366. or len(value) > 200
  6367. or any(unicodedata.category(character) == "Cc" for character in value)
  6368. ):
  6369. raise ValueError("runtimeSessionId is invalid")
  6370. return value
  6371. @classmethod
  6372. def _tool_state_json(cls, value: object) -> str:
  6373. if not isinstance(value, list):
  6374. raise ValueError("tool_state must be a list")
  6375. if not all(isinstance(item, Mapping) for item in value):
  6376. raise ValueError("tool_state entries must be objects")
  6377. encoded = cls._strict_json(value, "tool_state")
  6378. if len(encoded.encode("utf-8")) > MAX_TOOL_STATE_BYTES:
  6379. raise ValueError("tool_state exceeds maximum size")
  6380. return encoded
  6381. @classmethod
  6382. def _json_object(cls, value: object, field: str) -> str:
  6383. if not isinstance(value, Mapping):
  6384. raise ValueError(f"{field} must be an object")
  6385. encoded = cls._strict_json(dict(value), field)
  6386. if (
  6387. field == "payload"
  6388. and len(encoded.encode("utf-8")) > MAX_INTERACTION_PAYLOAD_BYTES
  6389. ):
  6390. raise ValueError("payload exceeds maximum size")
  6391. return encoded
  6392. @staticmethod
  6393. def _strict_json(value: object, field: str) -> str:
  6394. try:
  6395. encoded = json.dumps(
  6396. value,
  6397. ensure_ascii=False,
  6398. sort_keys=True,
  6399. separators=(",", ":"),
  6400. allow_nan=False,
  6401. )
  6402. encoded.encode("utf-8")
  6403. return encoded
  6404. except (TypeError, ValueError, UnicodeEncodeError) as error:
  6405. raise ValueError(f"{field} must be JSON-serializable") from error
  6406. @staticmethod
  6407. def _load_json(value: object) -> object:
  6408. if not isinstance(value, str):
  6409. raise ValueError("JSON must be a string")
  6410. return json.loads(
  6411. value,
  6412. parse_constant=lambda constant: (_ for _ in ()).throw(ValueError(constant)),
  6413. )
  6414. @staticmethod
  6415. def _page_limit(value: object, maximum: int, field: str) -> int:
  6416. if (
  6417. not isinstance(value, int)
  6418. or isinstance(value, bool)
  6419. or not 1 <= value <= maximum
  6420. ):
  6421. raise ValueError(f"{field} must be an integer from 1 to {maximum}")
  6422. return value
  6423. @staticmethod
  6424. def _positive_int(value: object, field: str) -> int:
  6425. if not isinstance(value, int) or isinstance(value, bool) or value < 1:
  6426. raise ValueError(f"{field} must be a positive integer")
  6427. return value
  6428. @staticmethod
  6429. def _nonnegative_int(value: object, field: str) -> int:
  6430. if not isinstance(value, int) or isinstance(value, bool) or value < 0:
  6431. raise ValueError(f"{field} must be a nonnegative integer")
  6432. return value
  6433. @staticmethod
  6434. def _finite_timestamp(value: object, field: str) -> float:
  6435. try:
  6436. finite = (
  6437. math.isfinite(value)
  6438. if isinstance(value, (int, float)) and not isinstance(value, bool)
  6439. else False
  6440. )
  6441. except OverflowError:
  6442. finite = False
  6443. if not finite:
  6444. raise ValueError(f"{field} must be finite")
  6445. return float(value)
  6446. def _new_agents(self, value: object) -> list[dict[str, object]]:
  6447. if not isinstance(value, list) or not 1 <= len(value) <= MAX_AGENTS_PER_ROOM:
  6448. raise ValueError(f"agents must contain 1 to {MAX_AGENTS_PER_ROOM} members")
  6449. agents = [self._new_agent(agent) for agent in value]
  6450. profiles = [agent["profile"] for agent in agents]
  6451. display_keys = [agent["display_name_key"] for agent in agents]
  6452. if len(profiles) != len(set(profiles)):
  6453. raise GroupConflictError("Agent profile must be unique within a room")
  6454. if len(display_keys) != len(set(display_keys)):
  6455. raise GroupConflictError("Agent display name must be unique within a room")
  6456. host_count = sum(bool(agent["is_host"]) for agent in agents)
  6457. if host_count > 1:
  6458. raise GroupConflictError("Room may contain only one host Agent")
  6459. if host_count == 0:
  6460. agents[0]["is_host"] = True
  6461. return agents
  6462. def _new_agent(self, command: object) -> dict[str, object]:
  6463. command = self._command(
  6464. command,
  6465. {
  6466. "profile", "displayName", "description", "replyWithoutMention",
  6467. "isHost",
  6468. "model", "provider", "reasoningEffort", "fastMode",
  6469. },
  6470. )
  6471. profile = self._profile(command.get("profile"))
  6472. raw_name = command.get("displayName")
  6473. explicit_name = (
  6474. raw_name.strip()
  6475. if isinstance(raw_name, str) and raw_name.strip()
  6476. else ""
  6477. )
  6478. display_name, display_name_key = normalize_display_name(
  6479. explicit_name or self._resolved_agent_name(profile) or profile
  6480. )
  6481. reply_without_mention = command.get("replyWithoutMention", False)
  6482. if not isinstance(reply_without_mention, bool):
  6483. raise ValueError("replyWithoutMention must be a boolean")
  6484. is_host = command.get("isHost", False)
  6485. if not isinstance(is_host, bool):
  6486. raise ValueError("isHost must be a boolean")
  6487. fast_mode = command.get("fastMode")
  6488. if fast_mode is not None and not isinstance(fast_mode, bool):
  6489. raise ValueError("fastMode must be a boolean or null")
  6490. if (command.get("model") is None) != (command.get("provider") is None):
  6491. raise ValueError("model and provider must both be set or both be null")
  6492. return {
  6493. "profile": profile,
  6494. "display_name": display_name,
  6495. "display_name_key": display_name_key,
  6496. "description": self._description(command.get("description", "")),
  6497. "reply_without_mention": reply_without_mention,
  6498. "is_host": is_host,
  6499. "model_override": self._agent_configuration_value(
  6500. command.get("model"), "model"
  6501. ),
  6502. "provider_override": self._agent_configuration_value(
  6503. command.get("provider"), "provider"
  6504. ),
  6505. "reasoning_effort_override": self._agent_configuration_value(
  6506. command.get("reasoningEffort"), "reasoningEffort"
  6507. ),
  6508. "fast_mode_override": fast_mode,
  6509. }
  6510. @staticmethod
  6511. def _agent_configuration_value(value: object, field: str) -> str | None:
  6512. if value is None:
  6513. return None
  6514. if not isinstance(value, str) or not value.strip():
  6515. raise ValueError(f"{field} must be a non-empty string or null")
  6516. normalized = value.strip()
  6517. if field == "reasoningEffort" and normalized not in {
  6518. "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
  6519. }:
  6520. raise ValueError("reasoningEffort is invalid")
  6521. return normalized
  6522. def _resolved_agent_name(self, profile: str) -> str:
  6523. try:
  6524. value = self._agent_name_resolver(profile)
  6525. except Exception as error:
  6526. raise GroupStoreError("Agent name settings could not be read") from error
  6527. if not isinstance(value, str):
  6528. raise GroupStoreError("Agent name settings are invalid")
  6529. normalized = value.strip()
  6530. return "" if is_reserved_mention_alias(normalized) else normalized
  6531. def _insert_agent(
  6532. self,
  6533. connection: sqlite3.Connection,
  6534. room_id: str,
  6535. agent: Mapping[str, object],
  6536. now: float,
  6537. ) -> str:
  6538. self._check_agent_conflicts(
  6539. connection, room_id, agent["display_name_key"], profile=agent["profile"]
  6540. )
  6541. agent_id = str(uuid.uuid4())
  6542. connection.execute(
  6543. """INSERT INTO group_agents
  6544. (id, room_id, profile, display_name, display_name_key, description,
  6545. reply_without_mention, is_host, model_override, provider_override,
  6546. reasoning_effort_override, fast_mode_override, created_at, updated_at)
  6547. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
  6548. (
  6549. agent_id,
  6550. room_id,
  6551. agent["profile"],
  6552. agent["display_name"],
  6553. agent["display_name_key"],
  6554. agent["description"],
  6555. int(bool(agent["reply_without_mention"])),
  6556. int(bool(agent["is_host"])),
  6557. agent["model_override"],
  6558. agent["provider_override"],
  6559. agent["reasoning_effort_override"],
  6560. None if agent["fast_mode_override"] is None
  6561. else int(bool(agent["fast_mode_override"])),
  6562. now,
  6563. now,
  6564. ),
  6565. )
  6566. connection.execute(
  6567. """INSERT INTO group_agent_topic_state
  6568. (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
  6569. SELECT ?, id, 0, ?, ? FROM group_topics WHERE room_id = ?""",
  6570. (agent_id, now, now, room_id),
  6571. )
  6572. return agent_id
  6573. @staticmethod
  6574. def _check_agent_conflicts(
  6575. connection: sqlite3.Connection,
  6576. room_id: str,
  6577. display_name_key: str,
  6578. *,
  6579. profile: str | None = None,
  6580. exclude_agent_id: str | None = None,
  6581. ) -> None:
  6582. exclusion = " AND id != ?" if exclude_agent_id is not None else ""
  6583. suffix: tuple[object, ...] = (
  6584. (exclude_agent_id,) if exclude_agent_id is not None else ()
  6585. )
  6586. if (
  6587. profile is not None
  6588. and connection.execute(
  6589. f"SELECT 1 FROM group_agents WHERE room_id = ? AND profile = ?{exclusion}",
  6590. (room_id, profile, *suffix),
  6591. ).fetchone()
  6592. is not None
  6593. ):
  6594. raise GroupConflictError("Agent profile must be unique within a room")
  6595. if (
  6596. connection.execute(
  6597. f"SELECT 1 FROM group_agents WHERE room_id = ? AND display_name_key = ?{exclusion}",
  6598. (room_id, display_name_key, *suffix),
  6599. ).fetchone()
  6600. is not None
  6601. ):
  6602. raise GroupConflictError("Agent display name must be unique within a room")
  6603. @staticmethod
  6604. def _room_wire(row: sqlite3.Row) -> dict[str, object]:
  6605. return {
  6606. "id": row["id"],
  6607. "name": row["name"],
  6608. "cwd": row["cwd"],
  6609. "instructions": row["instructions"],
  6610. "maxReplyRounds": row["max_reply_rounds"],
  6611. "orchestrationMode": row["orchestration_mode"],
  6612. "createdAt": row["created_at"],
  6613. "updatedAt": row["updated_at"],
  6614. "archived": bool(row["archived"]),
  6615. }
  6616. @staticmethod
  6617. def _room_summary(row: sqlite3.Row) -> dict[str, object]:
  6618. return {
  6619. "id": row["id"],
  6620. "name": row["name"],
  6621. "cwd": row["cwd"],
  6622. "instructions": row["instructions"],
  6623. "maxReplyRounds": row["max_reply_rounds"],
  6624. "orchestrationMode": row["orchestration_mode"],
  6625. "createdAt": row["created_at"],
  6626. "updatedAt": row["updated_at"],
  6627. "archived": False,
  6628. "agentCount": row["agent_count"],
  6629. "topicCount": row["topic_count"],
  6630. }
  6631. @staticmethod
  6632. def _topic_summary(row: sqlite3.Row) -> dict[str, object]:
  6633. preview = str(row["preview"] or "")
  6634. return {
  6635. "id": row["id"],
  6636. "roomId": row["room_id"],
  6637. "title": row["title"],
  6638. "preview": preview[:_TOPIC_PREVIEW_LENGTH],
  6639. "messageCount": int(row["message_count"]),
  6640. "unreadCount": int(row["unread_count"]),
  6641. "latestMessageSeq": int(row["latest_message_seq"]),
  6642. "lastReadMessageSeq": int(row["last_read_message_seq"]),
  6643. "archived": bool(row["archived"]),
  6644. "pinned": bool(row["pinned"]),
  6645. "createdAt": row["created_at"],
  6646. "updatedAt": row["updated_at"],
  6647. }
  6648. @staticmethod
  6649. def _agent_wire(row: sqlite3.Row) -> dict[str, object]:
  6650. return {
  6651. "id": row["id"],
  6652. "roomId": row["room_id"],
  6653. "profile": row["profile"],
  6654. "displayName": row["display_name"],
  6655. "description": row["description"],
  6656. "storedSessionId": row["stored_session_id"],
  6657. "lastContextMessageSeq": row["last_context_message_seq"],
  6658. "enabled": bool(row["enabled"]),
  6659. "replyWithoutMention": bool(row["reply_without_mention"]),
  6660. "isHost": bool(row["is_host"]),
  6661. "model": row["model_override"],
  6662. "provider": row["provider_override"],
  6663. "reasoningEffort": row["reasoning_effort_override"],
  6664. "fastMode": None if row["fast_mode_override"] is None
  6665. else bool(row["fast_mode_override"]),
  6666. "createdAt": row["created_at"],
  6667. "updatedAt": row["updated_at"],
  6668. }
  6669. @staticmethod
  6670. def _canonical_uuid(value: object, field: str) -> str:
  6671. if not isinstance(value, str):
  6672. raise ValueError(f"{field} must be a canonical UUID")
  6673. try:
  6674. canonical = str(uuid.UUID(value))
  6675. except ValueError as error:
  6676. raise ValueError(f"{field} must be a canonical UUID") from error
  6677. if value != canonical:
  6678. raise ValueError(f"{field} must be a canonical UUID")
  6679. return canonical
  6680. @staticmethod
  6681. def _canonical_json(value: object) -> str:
  6682. try:
  6683. encoded = json.dumps(
  6684. value,
  6685. ensure_ascii=False,
  6686. sort_keys=True,
  6687. separators=(",", ":"),
  6688. allow_nan=False,
  6689. )
  6690. encoded.encode("utf-8")
  6691. return encoded
  6692. except (TypeError, ValueError, UnicodeEncodeError) as error:
  6693. raise ValueError("value must be strict JSON") from error
  6694. @classmethod
  6695. def _interaction_response_operation(
  6696. cls, value: object
  6697. ) -> tuple[str, str | None] | None:
  6698. if not isinstance(value, str):
  6699. return None
  6700. base, separator, interaction_id = value.partition(":")
  6701. operations = {
  6702. "interaction.approval.response": "approval",
  6703. "interaction.clarification.response": "clarification",
  6704. }
  6705. kind = operations.get(base)
  6706. if kind is None:
  6707. return None
  6708. if not separator:
  6709. return kind, None
  6710. try:
  6711. canonical_interaction_id = cls._interaction_id(interaction_id)
  6712. except ValueError:
  6713. return None
  6714. if canonical_interaction_id != interaction_id:
  6715. return None
  6716. return kind, canonical_interaction_id
  6717. @classmethod
  6718. def _interaction_operation(cls, kind: str, interaction_id: str) -> str:
  6719. if kind not in _INTERACTION_KINDS:
  6720. raise GroupStoreError("Stored interaction kind is corrupt")
  6721. canonical_interaction_id = cls._interaction_id(interaction_id)
  6722. if canonical_interaction_id != interaction_id:
  6723. raise GroupStoreError("Stored interaction identity is corrupt")
  6724. return f"interaction.{kind}.response:{canonical_interaction_id}"
  6725. @classmethod
  6726. def _idempotency_state(cls, value: object) -> dict[str, object]:
  6727. try:
  6728. state = cls._load_json(value)
  6729. except (TypeError, ValueError, json.JSONDecodeError) as error:
  6730. raise GroupStoreError("Stored interaction response is corrupt") from error
  6731. if not isinstance(state, dict) or cls._canonical_json(state) != value:
  6732. raise GroupStoreError("Stored interaction response is corrupt")
  6733. status = state.get("state")
  6734. if status == "claimed":
  6735. if (
  6736. not isinstance(state.get("interactionId"), str)
  6737. or state.get("kind") not in _INTERACTION_KINDS
  6738. ):
  6739. raise GroupStoreError("Stored interaction response is corrupt")
  6740. elif status == "completed":
  6741. if not isinstance(state.get("response"), dict):
  6742. raise GroupStoreError("Stored interaction response is corrupt")
  6743. interaction_status = state.get("interactionStatus", "resolved")
  6744. if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
  6745. raise GroupStoreError("Stored interaction response is corrupt")
  6746. elif status == "failed":
  6747. runtime_ids = state.get("runtimeSessionIds")
  6748. if (
  6749. not isinstance(state.get("reason"), str)
  6750. or not isinstance(runtime_ids, list)
  6751. or not all(isinstance(item, str) for item in runtime_ids)
  6752. or len(runtime_ids) != len(set(runtime_ids))
  6753. or not isinstance(state.get("run"), dict)
  6754. ):
  6755. raise GroupStoreError("Stored interaction response is corrupt")
  6756. else:
  6757. raise GroupStoreError("Stored interaction response is corrupt")
  6758. return state
  6759. @staticmethod
  6760. def _runtime_envelope(response: dict[str, object]) -> dict[str, object]:
  6761. if "result" not in response and "runtimeSessionIds" not in response:
  6762. return {"result": response, "runtimeSessionIds": []}
  6763. result = response.get("result")
  6764. runtime_ids = response.get("runtimeSessionIds")
  6765. if not isinstance(result, dict) or not isinstance(runtime_ids, list):
  6766. raise GroupStoreError("Stored lifecycle response is corrupt")
  6767. if not all(isinstance(value, str) for value in runtime_ids):
  6768. raise GroupStoreError("Stored lifecycle response is corrupt")
  6769. if len(runtime_ids) != len(set(runtime_ids)):
  6770. raise GroupStoreError("Stored lifecycle response is corrupt")
  6771. return {"result": result, "runtimeSessionIds": runtime_ids}
  6772. @staticmethod
  6773. def _scoped_payload(
  6774. command: Mapping[str, object], room_id: str, agent_id: str | None = None
  6775. ) -> dict[str, object]:
  6776. payload: dict[str, object] = {"body": dict(command), "roomId": room_id}
  6777. if agent_id is not None:
  6778. payload["agentId"] = agent_id
  6779. return payload
  6780. @staticmethod
  6781. def _integrity_conflict(error: sqlite3.IntegrityError) -> GroupStoreError:
  6782. message = str(error)
  6783. if "group_agents.room_id, group_agents.profile" in message:
  6784. return GroupConflictError("Agent profile must be unique within a room")
  6785. if "group_agents.room_id, group_agents.display_name_key" in message:
  6786. return GroupConflictError("Agent display name must be unique within a room")
  6787. if "group_messages.client_message_id" in message:
  6788. return GroupConflictError("clientMessageId already exists")
  6789. if "group_agent_runs.runtime_session_id" in message:
  6790. return GroupConflictError("Runtime session is already in use")
  6791. return GroupStoreError("Group storage constraint failed")
  6792. @staticmethod
  6793. def _command(value: object, allowed: set[str]) -> dict[str, object]:
  6794. if not isinstance(value, Mapping) or not all(
  6795. isinstance(key, str) for key in value
  6796. ):
  6797. raise ValueError("command must be an object")
  6798. unexpected = set(value) - allowed
  6799. if unexpected:
  6800. raise ValueError(
  6801. f"Unexpected command fields: {', '.join(sorted(unexpected))}"
  6802. )
  6803. return dict(value)
  6804. def _command_request_id(self, command: Mapping[str, object]) -> str:
  6805. if "requestId" not in command:
  6806. raise ValueError("requestId is required")
  6807. return self._canonical_uuid(command["requestId"], "requestId")
  6808. @staticmethod
  6809. def _string(command: Mapping[str, object], key: str) -> str:
  6810. value = command.get(key)
  6811. if not isinstance(value, str):
  6812. raise ValueError(f"{key} must be a string")
  6813. return value
  6814. @staticmethod
  6815. def _profile(value: object) -> str:
  6816. if not isinstance(value, str):
  6817. raise ValueError("profile must be a string")
  6818. profile = value.strip()
  6819. if not 1 <= len(profile) <= 100:
  6820. raise ValueError("profile must contain 1 to 100 characters")
  6821. return profile
  6822. @staticmethod
  6823. def _description(value: object) -> str:
  6824. if not isinstance(value, str):
  6825. raise ValueError("description must be a string")
  6826. description = value.strip()
  6827. if len(description) > 500:
  6828. raise ValueError("description must contain at most 500 characters")
  6829. return description
  6830. @staticmethod
  6831. def _now() -> float:
  6832. return time.time()
  6833. @staticmethod
  6834. def _encode_cursor(updated_at: float, room_id: str) -> str:
  6835. raw = json.dumps([updated_at, room_id], separators=(",", ":")).encode()
  6836. return base64.urlsafe_b64encode(raw).decode().rstrip("=")
  6837. @classmethod
  6838. def _decode_cursor(cls, cursor: str) -> tuple[float, str]:
  6839. if (
  6840. not isinstance(cursor, str)
  6841. or not cursor
  6842. or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
  6843. ):
  6844. raise ValueError("cursor is malformed")
  6845. try:
  6846. raw = base64.b64decode(
  6847. cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
  6848. )
  6849. decoded = json.loads(raw.decode("utf-8"))
  6850. if (
  6851. not isinstance(decoded, list)
  6852. or len(decoded) != 2
  6853. or isinstance(decoded[0], bool)
  6854. or not isinstance(decoded[0], (int, float))
  6855. or not math.isfinite(decoded[0])
  6856. ):
  6857. raise ValueError
  6858. updated_at = float(decoded[0])
  6859. room_id = cls._canonical_uuid(decoded[1], "cursor room id")
  6860. if cursor != cls._encode_cursor(updated_at, room_id):
  6861. raise ValueError
  6862. return updated_at, room_id
  6863. except (
  6864. ValueError,
  6865. TypeError,
  6866. UnicodeDecodeError,
  6867. json.JSONDecodeError,
  6868. binascii.Error,
  6869. OverflowError,
  6870. ) as error:
  6871. raise ValueError("cursor is malformed") from error
  6872. @staticmethod
  6873. def _encode_topic_cursor(
  6874. room_id: str, updated_at: float, topic_id: str
  6875. ) -> str:
  6876. raw = json.dumps(
  6877. ["topic", room_id, updated_at, topic_id], separators=(",", ":")
  6878. ).encode()
  6879. return base64.urlsafe_b64encode(raw).decode().rstrip("=")
  6880. @classmethod
  6881. def _decode_topic_cursor(
  6882. cls, cursor: str, expected_room_id: str
  6883. ) -> tuple[float, str]:
  6884. if (
  6885. not isinstance(cursor, str)
  6886. or not cursor
  6887. or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
  6888. ):
  6889. raise ValueError("cursor is malformed")
  6890. try:
  6891. raw = base64.b64decode(
  6892. cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
  6893. )
  6894. decoded = json.loads(raw.decode("utf-8"))
  6895. if (
  6896. not isinstance(decoded, list)
  6897. or len(decoded) != 4
  6898. or decoded[0] != "topic"
  6899. or isinstance(decoded[2], bool)
  6900. or not isinstance(decoded[2], (int, float))
  6901. or not math.isfinite(decoded[2])
  6902. ):
  6903. raise ValueError
  6904. room_id = cls._canonical_uuid(decoded[1], "cursor room id")
  6905. updated_at = float(decoded[2])
  6906. topic_id = cls._canonical_uuid(decoded[3], "cursor topic id")
  6907. if cursor != cls._encode_topic_cursor(room_id, updated_at, topic_id):
  6908. raise ValueError
  6909. except (
  6910. ValueError,
  6911. TypeError,
  6912. UnicodeDecodeError,
  6913. json.JSONDecodeError,
  6914. binascii.Error,
  6915. OverflowError,
  6916. ) as error:
  6917. raise ValueError("cursor is malformed") from error
  6918. if room_id != expected_room_id:
  6919. raise ValueError("cursor does not belong to room")
  6920. return updated_at, topic_id