runner.py 275 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315
  1. """
  2. Agent Runner - Agent 执行引擎
  3. 核心职责:
  4. 1. 执行 Agent 任务(循环调用 LLM + 工具)
  5. 2. 记录执行轨迹(Trace + Messages + GoalTree)
  6. 3. 加载和注入技能(Skill)
  7. 4. 管理执行计划(GoalTree)
  8. 5. 支持续跑(continue)和回溯重跑(rewind)
  9. 参数分层:
  10. - Infrastructure: AgentRunner 构造时设置(trace_store, llm_call 等)
  11. - RunConfig: 每次 run 时指定(model, trace_id, after_sequence 等)
  12. - Messages: OpenAI SDK 格式的任务消息
  13. """
  14. import asyncio
  15. from copy import deepcopy
  16. import json
  17. import logging
  18. import os
  19. import uuid
  20. from dataclasses import dataclass, field
  21. from datetime import datetime
  22. from hashlib import sha256
  23. from typing import AsyncIterator, Optional, Dict, Any, List, Callable, Literal, Tuple, Union
  24. from cyber_agent.trace.models import Trace, Message
  25. from cyber_agent.trace.protocols import TraceStore
  26. from cyber_agent.trace.trace_id import generate_sub_trace_id
  27. from cyber_agent.trace.goal_models import GoalTree
  28. from cyber_agent.trace.compaction import (
  29. CompressionConfig,
  30. compress_completed_goals,
  31. estimate_tokens,
  32. needs_level2_compression,
  33. build_compression_prompt,
  34. )
  35. from cyber_agent.skill.models import Skill
  36. from cyber_agent.skill.skill_loader import load_skills_from_dir
  37. from cyber_agent.tools import ToolRegistry, get_tool_registry
  38. from cyber_agent.tools.approval import (
  39. ToolApprovalBatchV1,
  40. ToolApprovalCallV1,
  41. approval_grant,
  42. tool_argument_hash,
  43. )
  44. from cyber_agent.tools.errors import RecoverableToolExecutionError
  45. from cyber_agent.tools.builtin.knowledge import KnowledgeConfig
  46. from cyber_agent.core.memory import (
  47. MEMORY_IDENTITY_CONTEXT_KEY,
  48. MemoryConfig,
  49. compute_memory_identity,
  50. )
  51. from cyber_agent.core.dream import DreamScope
  52. from cyber_agent.core.run_snapshot import (
  53. RUN_CONFIG_SNAPSHOT_CONTEXT_KEY,
  54. RunConfigSnapshotError,
  55. RunConfigSnapshotV1,
  56. RunConfigSnapshotV2,
  57. load_run_config_snapshot,
  58. persist_run_config_snapshot,
  59. )
  60. from cyber_agent.core.agent_mode import (
  61. AGENT_MODE_CONTEXT_KEY,
  62. AgentMode,
  63. RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY,
  64. RECURSIVE_CHILD_EXECUTION_MODE_CONTEXT_KEY,
  65. RECURSIVE_MAX_PARALLEL_CHILDREN_CONTEXT_KEY,
  66. apply_policy_to_context,
  67. assert_removed_config_absent,
  68. policy_from_context,
  69. CURRENT_RECURSIVE_REVISION,
  70. policy_from_environment,
  71. require_mutable_trace_policy,
  72. validate_recursive_child_execution,
  73. )
  74. from cyber_agent.core.task_protocol import (
  75. RootTaskAnchor,
  76. ensure_task_protocol,
  77. initialize_task_progress,
  78. new_task_protocol,
  79. task_progress_artifact_refs,
  80. task_progress_at_revision,
  81. task_progress_readiness_error,
  82. rewind_task_progress,
  83. protocol_error_report,
  84. rebuild_pending_replans,
  85. )
  86. from cyber_agent.core.task_protocol_service import TaskProtocolService
  87. from cyber_agent.core.context_policy import (
  88. canonical_json,
  89. ContextPolicyError,
  90. normalize_root_task_anchor,
  91. persist_root_task_anchor,
  92. prune_context_access,
  93. render_recursive_context,
  94. get_authorized_context_snapshot,
  95. require_matching_root_task_anchor,
  96. require_root_task_anchor,
  97. replace_context_access,
  98. )
  99. from cyber_agent.core.resource_budget import (
  100. RESOURCE_BUDGET_CONTEXT_KEY,
  101. ResourceBudget,
  102. ResourceBudgetController,
  103. ResourceBudgetExceeded,
  104. ResourceBudgetStateError,
  105. )
  106. from cyber_agent.core.artifacts import (
  107. ArtifactRef,
  108. ArtifactResolver,
  109. MaterialIssue,
  110. ValidationMaterial,
  111. extract_artifact_refs,
  112. material_chars,
  113. material_content_hash,
  114. resolve_artifact_refs,
  115. )
  116. from cyber_agent.core.validation import (
  117. ValidationCheck,
  118. ValidationCheckSpec,
  119. LLMValidator,
  120. ScopeValidationResult,
  121. ValidationPolicy,
  122. ValidationResult,
  123. ValidationRun,
  124. ValidationScope,
  125. ValidatorSettings,
  126. persist_validation_policy,
  127. require_validation_policy,
  128. )
  129. from cyber_agent.core.validator_web import (
  130. PageFetcher,
  131. SerperWebSearchProvider,
  132. ValidatorToolLimits,
  133. ValidatorToolSession,
  134. ValidatorWebSearchProvider,
  135. )
  136. from cyber_agent.core.prompts import (
  137. DEFAULT_SYSTEM_PREFIX,
  138. TRUNCATION_HINT,
  139. TOOL_INTERRUPTED_MESSAGE,
  140. AGENT_INTERRUPTED_SUMMARY,
  141. AGENT_CONTINUE_HINT_TEMPLATE,
  142. TASK_NAME_GENERATION_SYSTEM_PROMPT,
  143. TASK_NAME_FALLBACK,
  144. SUMMARY_HEADER_TEMPLATE,
  145. build_summary_header,
  146. build_tool_interrupted_message,
  147. build_agent_continue_hint,
  148. )
  149. logger = logging.getLogger(__name__)
  150. class PendingToolApprovalRestored(RuntimeError):
  151. """Internal control flow: an orphaned call was restored to user approval."""
  152. @dataclass
  153. class ContextUsage:
  154. """Context 使用情况"""
  155. trace_id: str
  156. message_count: int
  157. token_count: int
  158. max_tokens: int
  159. usage_percent: float
  160. image_count: int = 0
  161. @dataclass
  162. class SideBranchContext:
  163. """侧分支上下文(压缩/反思/知识评估)"""
  164. type: Literal["compression", "reflection", "knowledge_eval"]
  165. branch_id: str
  166. start_head_seq: int # 侧分支起点的 head_seq
  167. start_sequence: int # 侧分支第一条消息的 sequence
  168. start_history_length: int # 侧分支起点的 history 长度
  169. start_iteration: int # 旧 Trace 兼容字段;不再用于轮次预算
  170. max_turns: int = 5 # 最大轮次
  171. turns_used: int = 0 # 已持久化的 assistant 轮次
  172. def to_dict(self) -> Dict[str, Any]:
  173. """转换为字典(用于持久化和传递给工具)"""
  174. return {
  175. "type": self.type,
  176. "branch_id": self.branch_id,
  177. "start_head_seq": self.start_head_seq,
  178. "start_sequence": self.start_sequence,
  179. "start_iteration": self.start_iteration,
  180. "max_turns": self.max_turns,
  181. "turns_used": self.turns_used,
  182. "is_side_branch": True,
  183. "started_at": datetime.now().isoformat(),
  184. }
  185. # ===== 运行配置 =====
  186. @dataclass
  187. class RunConfig:
  188. """
  189. 运行参数 — 控制 Agent 如何执行
  190. 分为模型层参数(由上游 agent 或用户决定)和框架层参数(由系统注入)。
  191. """
  192. # --- 模型层参数 ---
  193. model: str = "gpt-4o"
  194. temperature: float = 0.3
  195. max_iterations: int = 200
  196. tools: Optional[List[str]] = None # None = 按 tool_groups 过滤;显式列表 = 精确指定
  197. tool_groups: Optional[List[str]] = field(default_factory=lambda: ["core"]) # 工具分组白名单;默认仅 core,项目按需追加
  198. exclude_tools: List[str] = field(default_factory=list) # 从 tools / tool_groups 结果中再排除的工具名(如远程 agent 禁用 agent/evaluate)
  199. side_branch_max_turns: int = 5 # 侧分支最大轮次(压缩/反思)
  200. goal_compression: Literal["none", "on_complete", "on_overflow"] = "on_overflow" # Goal 压缩模式
  201. # --- 强制侧分支(用于 API 手动触发或自动压缩流程)---
  202. # 使用列表作为侧分支队列,每次完成一个侧分支后 pop(0) 取下一个
  203. force_side_branch: Optional[List[Literal["compression", "reflection"]]] = None
  204. # --- 框架层参数 ---
  205. agent_type: str = "default"
  206. uid: Optional[str] = None
  207. system_prompt: Optional[str] = None # None = 从 skills 自动构建
  208. skills: Optional[List[str]] = None # 注入 system prompt 的 skill 名称列表;None = 按 preset 决定
  209. enable_memory: bool = True
  210. auto_execute_tools: bool = True
  211. name: Optional[str] = None # 显示名称(空则由 utility_llm 自动生成)
  212. enable_prompt_caching: bool = True # 启用 Anthropic Prompt Caching(仅 Claude 模型有效)
  213. parallel_tool_execution: bool = False # 是否启用并发 Tool Call 执行(慎用,需确保无资源冲突)
  214. child_execution_mode: Literal["sequential", "parallel"] = "sequential"
  215. max_parallel_children: int = 2
  216. root_task_anchor: Optional[RootTaskAnchor] = None
  217. # --- Trace 控制 ---
  218. trace_id: Optional[str] = None # None = 新建
  219. parent_trace_id: Optional[str] = None # 子 Agent 专用
  220. parent_goal_id: Optional[str] = None
  221. # --- 续跑控制 ---
  222. after_sequence: Optional[int] = None # 从哪条消息后续跑(message sequence)
  223. # --- 额外 LLM 参数(传给 llm_call 的 **kwargs)---
  224. extra_llm_params: Dict[str, Any] = field(default_factory=dict)
  225. # --- 自定义元数据上下文 ---
  226. context: Dict[str, Any] = field(default_factory=dict)
  227. # --- 研究流程控制 ---
  228. enable_research_flow: bool = True # 是否启用自动研究流程(知识检索→经验检索→调研→计划)
  229. # --- 知识管理配置 ---
  230. knowledge: KnowledgeConfig = field(default_factory=KnowledgeConfig)
  231. # --- Memory 配置(见 cyber_agent/docs/framework/runtime/memory.md) ---
  232. # None = 默认 Agent(无长期记忆);赋值 MemoryConfig 使该 Agent 成为 memory-bearing Agent
  233. memory: Optional["MemoryConfig"] = None
  234. # --- 一次性恢复动作(不进入持久化 RunConfigSnapshot) ---
  235. approval_batch_id: Optional[str] = None
  236. # --- ApplicationRuntime 固化身份(只由框架装配) ---
  237. application_ref: Any = None
  238. role_id: Optional[str] = None
  239. role_hash: Optional[str] = None
  240. effective_run_limits: Dict[str, Any] = field(default_factory=dict)
  241. def apply_snapshot(
  242. self,
  243. snapshot: RunConfigSnapshotV1 | RunConfigSnapshotV2,
  244. ) -> None:
  245. """Restore all persisted behavior fields while retaining invocation routing."""
  246. self.model = snapshot.model
  247. self.temperature = snapshot.temperature
  248. self.max_iterations = snapshot.max_iterations
  249. self.extra_llm_params = dict(snapshot.extra_llm_params)
  250. self.tools = list(snapshot.tools) if snapshot.tools is not None else None
  251. self.tool_groups = (
  252. list(snapshot.tool_groups) if snapshot.tool_groups is not None else None
  253. )
  254. self.exclude_tools = list(snapshot.exclude_tools)
  255. self.auto_execute_tools = snapshot.auto_execute_tools
  256. self.agent_type = snapshot.agent_type
  257. self.uid = snapshot.uid
  258. self.skills = list(snapshot.skills) if snapshot.skills is not None else None
  259. self.enable_memory = snapshot.enable_memory
  260. self.memory = MemoryConfig(**snapshot.memory) if snapshot.memory else None
  261. self.knowledge = KnowledgeConfig(**snapshot.knowledge)
  262. self.parallel_tool_execution = snapshot.parallel_tool_execution
  263. self.child_execution_mode = snapshot.child_execution_mode
  264. self.max_parallel_children = snapshot.max_parallel_children
  265. self.side_branch_max_turns = snapshot.side_branch_max_turns
  266. self.goal_compression = snapshot.goal_compression
  267. self.enable_prompt_caching = snapshot.enable_prompt_caching
  268. self.enable_research_flow = snapshot.enable_research_flow
  269. self.context = dict(snapshot.custom_context)
  270. if isinstance(snapshot, RunConfigSnapshotV2):
  271. self.application_ref = dict(snapshot.application_ref)
  272. self.role_id = snapshot.role_id
  273. self.role_hash = snapshot.role_hash
  274. self.effective_run_limits = dict(snapshot.effective_run_limits)
  275. # BUILTIN_TOOLS 硬编码列表已移除(2026-04)。
  276. # 工具可用性现在由 @tool(groups=[...]) 声明 + RunConfig.tool_groups 过滤控制。
  277. @dataclass
  278. class CallResult:
  279. """单次调用结果"""
  280. reply: str
  281. tool_calls: Optional[List[Dict]] = None
  282. trace_id: Optional[str] = None
  283. step_id: Optional[str] = None
  284. tokens: Optional[Dict[str, int]] = None
  285. cost: float = 0.0
  286. # ===== 执行引擎 =====
  287. CONTEXT_INJECTION_INTERVAL = 5 # 每 N 轮注入一次 GoalTree + Collaborators + IM 通知
  288. class AgentRunner:
  289. """
  290. Agent 执行引擎
  291. 支持三种运行模式(通过 RunConfig 区分):
  292. 1. 新建:trace_id=None
  293. 2. 续跑:trace_id=已有ID, after_sequence=None 或 == head
  294. 3. 回溯:trace_id=已有ID, after_sequence=N(N < head_sequence)
  295. """
  296. def __init__(
  297. self,
  298. trace_store: Optional[TraceStore] = None,
  299. tool_registry: Optional[ToolRegistry] = None,
  300. llm_call: Optional[Callable] = None,
  301. utility_llm_call: Optional[Callable] = None,
  302. skills_dir: Optional[str] = None,
  303. goal_tree: Optional[GoalTree] = None,
  304. debug: bool = False,
  305. logger_name: Optional[str] = None,
  306. validation_policy: Optional[ValidationPolicy] = None,
  307. validator_search_provider: Optional[ValidatorWebSearchProvider] = None,
  308. validator_page_fetcher: Optional[PageFetcher] = None,
  309. artifact_resolver: Optional[ArtifactResolver] = None,
  310. application_binding: Any = None,
  311. context_provider: Any = None,
  312. candidate_service: Any = None,
  313. event_service: Any = None,
  314. ):
  315. """
  316. 初始化 AgentRunner
  317. Args:
  318. trace_store: Trace 存储
  319. tool_registry: 工具注册表(默认使用全局注册表)
  320. llm_call: 主 LLM 调用函数
  321. utility_llm_call: 轻量 LLM(用于生成任务标题等),可选
  322. skills_dir: Skills 目录路径
  323. goal_tree: 初始 GoalTree(可选)
  324. debug: 保留参数(已废弃)
  325. logger_name: 自定义日志名称(如 "agents.knowledge_manager"),默认用模块名
  326. validation_policy: Recursive 根 Trace 固化的可信验收策略
  327. validator_search_provider: Validator 私有网页搜索适配器
  328. validator_page_fetcher: Validator 受控页面读取适配器
  329. artifact_resolver: Validator 只读产物解析器
  330. """
  331. self.trace_store = trace_store
  332. self.tools = tool_registry or get_tool_registry()
  333. self.llm_call = llm_call
  334. self.utility_llm_call = utility_llm_call
  335. self.skills_dir = skills_dir
  336. self.goal_tree = goal_tree
  337. self.debug = debug
  338. self.log = logging.getLogger(logger_name) if logger_name else logger
  339. self.validation_policy = validation_policy or ValidationPolicy()
  340. self.validator_search_provider = validator_search_provider
  341. self.validator_page_fetcher = validator_page_fetcher
  342. self.artifact_resolver = artifact_resolver
  343. self.application_binding = application_binding
  344. self.context_provider = context_provider
  345. self.candidate_service = candidate_service
  346. self.event_service = event_service
  347. self.stdin_check: Optional[Callable] = None # 由外部设置,用于子 agent 执行期间检查 stdin
  348. self._cancel_events: Dict[str, asyncio.Event] = {} # trace_id → cancel event
  349. self._recursive_active_traces: Dict[str, asyncio.Event] = {}
  350. self._active_children: Dict[str, set[str]] = {}
  351. self._active_parents: Dict[str, str] = {}
  352. # 知识保存跟踪(每个 trace 独立)
  353. self._saved_knowledge_ids: Dict[str, List[str]] = {} # trace_id → [knowledge_ids]
  354. # Context 使用跟踪
  355. self._context_warned: Dict[str, set] = {} # trace_id → {30, 50, 80} 已警告过的阈值
  356. self._context_usage: Dict[str, ContextUsage] = {} # trace_id → 当前用量快照
  357. # 图片优化缓存(避免重复处理)
  358. # key: 图片内容的 hash, value: {"downscaled": ..., "description": ...}
  359. self._image_opt_cache: Dict[str, Dict[str, Any]] = {}
  360. self.resource_budget = (
  361. ResourceBudgetController(trace_store) if trace_store else None
  362. )
  363. self.task_protocol_service = (
  364. TaskProtocolService(trace_store, event_service) if trace_store else None
  365. )
  366. # ===== 核心公开方法 =====
  367. def get_context_usage(self, trace_id: str) -> Optional[ContextUsage]:
  368. """获取指定 trace 的 context 使用情况"""
  369. return self._context_usage.get(trace_id)
  370. async def _resource_budget_for_trace(
  371. self,
  372. trace_id: str,
  373. ) -> tuple[str, ResourceBudget] | None:
  374. """解析本地 Trace 所属 Recursive 根树的不可变预算快照。
  375. 由模型调用、工具用量记账和子 Agent 创建入口调用;Legacy Trace 直接返回无预算。
  376. """
  377. if not self.trace_store:
  378. return None
  379. trace = await self.trace_store.get_trace(trace_id)
  380. if not trace or not policy_from_context(trace.context).requires_task_protocol:
  381. return None
  382. root_trace_id = trace.context.get("root_trace_id") or trace.trace_id
  383. root = trace if root_trace_id == trace.trace_id else await self.trace_store.get_trace(root_trace_id)
  384. if not root:
  385. raise ResourceBudgetStateError(
  386. f"Recursive root Trace not found: {root_trace_id}"
  387. )
  388. snapshot = root.context.get(RESOURCE_BUDGET_CONTEXT_KEY)
  389. if snapshot is None:
  390. raise ResourceBudgetStateError(
  391. "Recursive tree has no persisted resource budget; create a new trace"
  392. )
  393. return root_trace_id, ResourceBudget.from_dict(snapshot)
  394. async def call_recursive_llm(
  395. self,
  396. trace_id: str,
  397. *,
  398. purpose: Literal["ordinary", "root_validator"] = "ordinary",
  399. call: Optional[Callable] = None,
  400. fail_on_post_response_exhaustion: bool = False,
  401. **kwargs: Any,
  402. ) -> Dict[str, Any]:
  403. """Recursive 树中统一的 LLM 调用和资源记账入口。
  404. Agent 主循环、上下文压缩、图片描述和 Validator 共用;请求前预留次数,响应后记账。
  405. """
  406. llm = call or self.llm_call
  407. if not llm:
  408. raise ValueError("llm_call function not provided")
  409. resolved = await self._resource_budget_for_trace(trace_id)
  410. if resolved is None:
  411. return await llm(**kwargs)
  412. root_trace_id, budget = resolved
  413. if not self.resource_budget:
  414. raise ResourceBudgetStateError("ResourceBudgetController is unavailable")
  415. await self.resource_budget.reserve_llm_call(
  416. root_trace_id,
  417. budget,
  418. purpose=purpose,
  419. )
  420. result = await llm(**kwargs)
  421. try:
  422. await self.resource_budget.record_llm_usage(
  423. root_trace_id,
  424. budget,
  425. prompt_tokens=int(result.get("prompt_tokens", 0) or 0),
  426. completion_tokens=int(result.get("completion_tokens", 0) or 0),
  427. cost_usd=float(result.get("cost", 0) or 0),
  428. )
  429. except ResourceBudgetExceeded as exc:
  430. if fail_on_post_response_exhaustion:
  431. raise
  432. result = dict(result)
  433. result["_resource_budget_exceeded"] = exc.dimension
  434. return result
  435. async def record_recursive_tool_usage(
  436. self,
  437. trace_id: str,
  438. tool_usage: Dict[str, Any],
  439. ) -> None:
  440. """登记工具内部自行发起的模型用量。
  441. Agent 主循环在 Tool Result 携带 ``tool_usage`` 时调用,并计入同一棵 Recursive 树。
  442. """
  443. resolved = await self._resource_budget_for_trace(trace_id)
  444. if resolved is None:
  445. return
  446. root_trace_id, budget = resolved
  447. if not self.resource_budget:
  448. raise ResourceBudgetStateError("ResourceBudgetController is unavailable")
  449. await self.resource_budget.record_external_llm_usage(
  450. root_trace_id,
  451. budget,
  452. prompt_tokens=int(tool_usage.get("prompt_tokens", 0) or 0),
  453. completion_tokens=int(tool_usage.get("completion_tokens", 0) or 0),
  454. cost_usd=float(tool_usage.get("cost", 0) or 0),
  455. )
  456. async def record_recursive_validation_usage(
  457. self,
  458. trace_id: str,
  459. *,
  460. tool_calls: int = 0,
  461. material_chars_count: int = 0,
  462. provider_cost_usd: float = 0.0,
  463. operation_id: str | None = None,
  464. ) -> None:
  465. """把 Validator网页工具和真实材料字符计入同一棵树的预算。"""
  466. resolved = await self._resource_budget_for_trace(trace_id)
  467. if resolved is None:
  468. return
  469. root_trace_id, budget = resolved
  470. if not self.resource_budget:
  471. raise ResourceBudgetStateError("ResourceBudgetController is unavailable")
  472. await self.resource_budget.record_validation_usage(
  473. root_trace_id,
  474. budget,
  475. tool_calls=tool_calls,
  476. material_chars=material_chars_count,
  477. provider_cost_usd=provider_cost_usd,
  478. operation_id=operation_id,
  479. )
  480. async def validate_recursive_trace(
  481. self,
  482. evaluated_trace_id: str,
  483. *,
  484. scope: Optional[ValidationScope] = None,
  485. task_brief: Optional[Dict[str, Any]] = None,
  486. task_report: Optional[Dict[str, Any]] = None,
  487. completion_criteria: Optional[List[str]] = None,
  488. expected_outputs: Optional[List[str]] = None,
  489. candidate_output: Optional[str] = None,
  490. deterministic_failure: Optional[Dict[str, Any]] = None,
  491. root_validator: bool = False,
  492. candidate_ref: Any = None,
  493. ) -> ValidationRun:
  494. """编译Plan、解析材料、顺序运行Scope并持久化聚合缓存。"""
  495. if not self.trace_store or not self.llm_call:
  496. raise RuntimeError("Validator requires trace_store and llm_call")
  497. evaluated = await self.trace_store.get_trace(evaluated_trace_id)
  498. if not evaluated:
  499. raise ValueError(f"Trace not found: {evaluated_trace_id}")
  500. root_trace_id = evaluated.context.get("root_trace_id") or evaluated.trace_id
  501. root = (
  502. evaluated
  503. if root_trace_id == evaluated.trace_id
  504. else await self.trace_store.get_trace(root_trace_id)
  505. )
  506. if not root:
  507. raise ContextPolicyError(f"Recursive root Trace not found: {root_trace_id}")
  508. root_anchor = require_matching_root_task_anchor(
  509. root.context,
  510. evaluated.context,
  511. )
  512. policy, settings = require_validation_policy(root.context)
  513. state = ensure_task_protocol(evaluated.context)
  514. if candidate_ref is not None:
  515. from cyber_agent.application.candidate import CandidateRef
  516. candidate_ref = CandidateRef.model_validate(candidate_ref)
  517. if self.candidate_service is None:
  518. raise ValueError("Candidate validation requires CandidateService")
  519. if root_validator:
  520. raise ValueError("Candidate validation cannot be root validation")
  521. runtime_policy = policy_from_context(evaluated.context)
  522. authoritative_brief = state.get("task_brief")
  523. if authoritative_brief is not None:
  524. task_brief = authoritative_brief
  525. task_brief_version = int(state.get("task_brief_version", 0) or 0)
  526. progress_revision = (
  527. state.get("task_progress_head_revision")
  528. if root_validator or task_report is None
  529. else state.get("task_report_progress_revision")
  530. )
  531. task_progress = task_progress_at_revision(state, progress_revision)
  532. if runtime_policy.requires_task_progress and task_progress is None:
  533. raise ValueError("Recursive revision 3 validation requires TaskProgress")
  534. trajectory = await self.trace_store.get_main_path_messages(
  535. evaluated_trace_id,
  536. evaluated.head_sequence or evaluated.last_sequence,
  537. )
  538. refs: list[ArtifactRef] = []
  539. materials: list[ValidationMaterial] = []
  540. source_urls: list[str] = []
  541. material_issues: list[MaterialIssue] = []
  542. try:
  543. if isinstance(task_report, dict):
  544. refs.extend(extract_artifact_refs(task_report))
  545. source_urls = list(task_report.get("source_urls") or [])
  546. refs.extend(task_progress_artifact_refs(task_progress))
  547. if task_progress is not None:
  548. for item in (
  549. *task_progress.questions,
  550. *task_progress.blockers,
  551. *task_progress.findings,
  552. *task_progress.hypotheses,
  553. *task_progress.work_items,
  554. ):
  555. for ref in item.context_refs:
  556. snapshot = get_authorized_context_snapshot(
  557. evaluated.context,
  558. ref_id=ref.ref_id,
  559. version=ref.version,
  560. root_trace_id=root_trace_id,
  561. uid=evaluated.uid,
  562. )
  563. materials.append(ValidationMaterial(
  564. artifact_id=ref.ref_id,
  565. version=snapshot.version,
  566. content_hash=snapshot.version,
  567. kind=f"context.{snapshot.kind}",
  568. mime_type="application/json",
  569. root_trace_id=root_trace_id,
  570. uid=evaluated.uid,
  571. content=snapshot.content,
  572. ))
  573. if root_validator:
  574. for message in trajectory:
  575. if message.role == "tool" and isinstance(message.content, dict):
  576. refs.extend(extract_artifact_refs(message.content))
  577. except Exception as exc:
  578. material_issues.append(MaterialIssue(
  579. artifact_id="artifact_metadata",
  580. outcome="error",
  581. reason=f"Invalid artifact metadata: {exc}",
  582. ))
  583. unique_refs = {
  584. (item.artifact_id, item.version, item.content_hash): item for item in refs
  585. }
  586. resolved_materials, resolved_issues = await resolve_artifact_refs(
  587. list(unique_refs.values()),
  588. resolver=self.artifact_resolver,
  589. root_trace_id=root_trace_id,
  590. uid=evaluated.uid,
  591. )
  592. materials.extend(resolved_materials)
  593. material_issues.extend(resolved_issues)
  594. candidate_material = None
  595. if candidate_ref is not None:
  596. try:
  597. candidate_material = await self.candidate_service.resolve_for_validation(
  598. evaluated_trace_id,
  599. candidate_ref,
  600. )
  601. materials = [
  602. item for item in materials
  603. if not (
  604. item.artifact_id == candidate_material.artifact_id
  605. and item.version == candidate_material.version
  606. )
  607. ]
  608. materials.append(candidate_material)
  609. candidate_output = json.dumps(
  610. candidate_material.content,
  611. ensure_ascii=False,
  612. sort_keys=True,
  613. separators=(",", ":"),
  614. )
  615. except Exception as exc:
  616. material_issues.append(MaterialIssue(
  617. artifact_id=candidate_ref.artifact_ref.artifact_id,
  618. outcome="error",
  619. reason=f"Candidate material cannot be resolved: {exc}",
  620. scopes=["output"],
  621. ))
  622. total_material_chars = sum(material_chars(item) for item in materials)
  623. if deterministic_failure:
  624. material_issues.append(MaterialIssue(
  625. artifact_id="execution",
  626. outcome=deterministic_failure.get("outcome", "error"),
  627. reason=deterministic_failure.get("reason", "Task did not complete"),
  628. ))
  629. default_model = settings.validator_model or evaluated.model or ""
  630. root_model = settings.root_validator_model or default_model
  631. model_by_scope = {
  632. item: (root_model if item == "root" else default_model)
  633. for item in ("evidence", "hypothesis", "output", "task", "root")
  634. }
  635. if scope == "root" or root_validator:
  636. root_validator = True
  637. elif scope and task_brief is None:
  638. task_brief = {
  639. "completion_criteria": completion_criteria or [],
  640. "expected_outputs": expected_outputs or [],
  641. "validation_scopes": [] if scope == "task" else [scope],
  642. }
  643. validation_subject = None
  644. quality_specs: list[ValidationCheckSpec] = []
  645. quality_manifest: list[dict[str, Any]] = []
  646. fixed_checks: dict[str, ValidationCheck] = {}
  647. fixed_scope_errors: dict[ValidationScope, str] = {}
  648. quality_rules: tuple[Any, ...] = ()
  649. quality_materials: tuple[ValidationMaterial, ...] = ()
  650. if self.application_binding is not None:
  651. from cyber_agent.application.quality import ValidationSubject
  652. brief_payload = (
  653. task_brief.model_dump(mode="json")
  654. if hasattr(task_brief, "model_dump")
  655. else (task_brief or {})
  656. )
  657. requested_quality_scopes = (
  658. {"output"}
  659. if candidate_ref is not None
  660. else set(policy.effective_scopes(
  661. brief_payload.get("validation_scopes", []),
  662. root=root_validator,
  663. ))
  664. )
  665. validation_subject = ValidationSubject(
  666. subject_type=("candidate" if candidate_ref is not None else "trace"),
  667. trace_id=evaluated_trace_id,
  668. candidate_ref=candidate_ref,
  669. )
  670. quality_rules = tuple(
  671. rule
  672. for rule in self.application_binding.application.quality_rules
  673. if validation_subject.subject_type in rule.subject_types
  674. and rule.scope in requested_quality_scopes
  675. )
  676. if candidate_ref is not None and candidate_material is not None:
  677. quality_materials = (candidate_material,)
  678. elif candidate_ref is None:
  679. quality_materials = tuple(materials)
  680. if isinstance(task_report, dict):
  681. report_material = ValidationMaterial(
  682. artifact_id=f"trace:{evaluated_trace_id}:task_report",
  683. version=str(progress_revision or 0),
  684. content_hash=material_content_hash(task_report),
  685. kind="framework.task_report",
  686. mime_type="application/json",
  687. root_trace_id=root_trace_id,
  688. uid=evaluated.uid,
  689. content=task_report,
  690. )
  691. quality_materials = (*quality_materials, report_material)
  692. total_material_chars += material_chars(report_material)
  693. quality_specs = [
  694. ValidationCheckSpec(
  695. check_id=f"quality.{rule.rule_id}",
  696. scope=rule.scope,
  697. criterion=rule.criterion,
  698. method="deterministic",
  699. )
  700. for rule in quality_rules
  701. ]
  702. quality_manifest = [
  703. item.model_dump(mode="json") for item in quality_rules
  704. ]
  705. plan = policy.compile_plan(
  706. task_brief=task_brief,
  707. task_brief_version=task_brief_version,
  708. root_task_anchor=root_anchor,
  709. task_report=task_report,
  710. candidate_output=candidate_output,
  711. evaluated_head_sequence=(
  712. candidate_ref.created_at_sequence
  713. if candidate_ref is not None
  714. else (evaluated.head_sequence or evaluated.last_sequence)
  715. ),
  716. materials=materials,
  717. material_issues=material_issues,
  718. model_by_scope=model_by_scope,
  719. root=root_validator,
  720. task_progress=task_progress,
  721. subject=validation_subject,
  722. quality_checks=quality_specs,
  723. quality_manifest=quality_manifest,
  724. )
  725. cached = state.get("task_report_validation")
  726. if candidate_ref is not None:
  727. candidate_cached = await self.candidate_service.cached_validation(
  728. evaluated_trace_id,
  729. candidate_ref,
  730. plan.plan_hash,
  731. )
  732. if candidate_cached is not None:
  733. aggregate = ValidationResult.model_validate(
  734. candidate_cached.validation_result
  735. )
  736. return ValidationRun(
  737. result=aggregate,
  738. trace_ids=[
  739. item.validator_trace_id
  740. for item in aggregate.scope_results
  741. ],
  742. cached=True,
  743. )
  744. cached = None
  745. validation_cache: dict[str, Any]
  746. resume_scope_results: list[ScopeValidationResult] = []
  747. if isinstance(cached, dict) and cached.get("plan_hash") == plan.plan_hash:
  748. validation_cache = cached
  749. try:
  750. aggregate_raw = cached.get("aggregate_result")
  751. if aggregate_raw:
  752. aggregate = ValidationResult.model_validate(aggregate_raw)
  753. if (
  754. aggregate.evaluated_trace_id == evaluated_trace_id
  755. and aggregate.plan_hash == plan.plan_hash
  756. ):
  757. return ValidationRun(
  758. result=aggregate,
  759. trace_ids=[
  760. item.validator_trace_id
  761. for item in aggregate.scope_results
  762. ],
  763. cached=True,
  764. )
  765. resume_scope_results = [
  766. ScopeValidationResult.model_validate(item)
  767. for item in cached.get("scope_results", [])
  768. ]
  769. except Exception:
  770. resume_scope_results = []
  771. else:
  772. validation_cache = {
  773. "validation_plan": plan.model_dump(mode="json"),
  774. "plan_hash": plan.plan_hash,
  775. "scope_results": [],
  776. "aggregate_result": None,
  777. "validated_at_sequence": plan.evaluated_head_sequence,
  778. "material_usage_recorded": total_material_chars == 0,
  779. }
  780. if candidate_ref is None:
  781. assert self.task_protocol_service is not None
  782. await self.task_protocol_service.mutate_state(
  783. evaluated_trace_id,
  784. lambda _trace, fresh_state: fresh_state.__setitem__(
  785. "task_report_validation",
  786. deepcopy(validation_cache),
  787. ),
  788. )
  789. candidate_checkpoint = None
  790. if candidate_ref is not None:
  791. candidate_checkpoint = await self.candidate_service.begin_validation_checkpoint(
  792. evaluated_trace_id,
  793. candidate_ref,
  794. plan=plan.model_dump(mode="json"),
  795. plan_hash=plan.plan_hash,
  796. validated_at_sequence=plan.evaluated_head_sequence,
  797. material_usage_recorded=total_material_chars == 0,
  798. )
  799. validation_cache = {
  800. "validation_plan": candidate_checkpoint.validation_plan,
  801. "plan_hash": candidate_checkpoint.plan_hash,
  802. "scope_results": list(candidate_checkpoint.scope_results),
  803. "aggregate_result": candidate_checkpoint.aggregate_result,
  804. "validated_at_sequence": candidate_checkpoint.validated_at_sequence,
  805. "material_usage_recorded": (
  806. candidate_checkpoint.material_usage_recorded
  807. ),
  808. }
  809. resume_scope_results = [
  810. ScopeValidationResult.model_validate(item)
  811. for item in candidate_checkpoint.scope_results
  812. ]
  813. if quality_rules:
  814. if candidate_checkpoint.quality_completed:
  815. fixed_checks = {
  816. item["check_id"]: ValidationCheck.model_validate(item)
  817. for item in candidate_checkpoint.fixed_checks
  818. }
  819. fixed_scope_errors = {
  820. key: value
  821. for key, value in candidate_checkpoint.fixed_scope_errors.items()
  822. }
  823. else:
  824. fixed_checks, fixed_scope_errors = await self._run_quality_checks(
  825. validation_subject,
  826. quality_materials,
  827. quality_rules,
  828. usage_operation_prefix=(
  829. f"candidate-validation:{candidate_ref.candidate_id}:"
  830. f"{candidate_ref.revision}:{plan.plan_hash}"
  831. ),
  832. )
  833. candidate_checkpoint = (
  834. await self.candidate_service.update_validation_checkpoint(
  835. evaluated_trace_id,
  836. candidate_ref,
  837. plan.plan_hash,
  838. fixed_checks=tuple(
  839. item.model_dump(mode="json")
  840. for item in fixed_checks.values()
  841. ),
  842. fixed_scope_errors={
  843. key: value
  844. for key, value in fixed_scope_errors.items()
  845. },
  846. quality_completed=True,
  847. )
  848. )
  849. if candidate_ref is None and quality_rules:
  850. fixed_checks, fixed_scope_errors = await self._run_quality_checks(
  851. validation_subject,
  852. quality_materials,
  853. quality_rules,
  854. usage_operation_prefix=(
  855. f"trace-validation:{evaluated_trace_id}:{plan.plan_hash}"
  856. ),
  857. )
  858. if (
  859. total_material_chars
  860. and not validation_cache.get("material_usage_recorded", False)
  861. ):
  862. await self.record_recursive_validation_usage(
  863. evaluated_trace_id,
  864. material_chars_count=total_material_chars,
  865. operation_id=(
  866. f"validation-materials:{evaluated_trace_id}:{plan.plan_hash}"
  867. ),
  868. )
  869. if candidate_ref is not None:
  870. validation_cache["material_usage_recorded"] = True
  871. candidate_checkpoint = (
  872. await self.candidate_service.update_validation_checkpoint(
  873. evaluated_trace_id,
  874. candidate_ref,
  875. plan.plan_hash,
  876. material_usage_recorded=True,
  877. )
  878. )
  879. else:
  880. assert self.task_protocol_service is not None
  881. def mark_material_usage(_trace, fresh_state):
  882. fresh_cache = fresh_state.get("task_report_validation")
  883. if (
  884. not isinstance(fresh_cache, dict)
  885. or fresh_cache.get("plan_hash") != plan.plan_hash
  886. ):
  887. raise ValueError(
  888. "Validation cache changed while recording materials"
  889. )
  890. fresh_cache["material_usage_recorded"] = True
  891. await self.task_protocol_service.mutate_state(
  892. evaluated_trace_id,
  893. mark_material_usage,
  894. )
  895. lineage_event = None
  896. if (
  897. evaluated.parent_trace_id
  898. and evaluated_trace_id not in self._recursive_active_traces
  899. ):
  900. lineage_event = self.register_recursive_child(
  901. evaluated.parent_trace_id,
  902. evaluated_trace_id,
  903. )
  904. async def validator_llm_call(**kwargs: Any) -> Dict[str, Any]:
  905. result = await self.call_recursive_llm(
  906. evaluated_trace_id,
  907. purpose="root_validator" if root_validator else "ordinary",
  908. **kwargs,
  909. )
  910. dimension = result.get("_resource_budget_exceeded")
  911. if dimension:
  912. raise RuntimeError(
  913. f"Validator exceeded tree resource budget: {dimension}"
  914. )
  915. return result
  916. provider: ValidatorWebSearchProvider | None
  917. if settings.search_provider == "disabled":
  918. provider = None
  919. else:
  920. provider = self.validator_search_provider or SerperWebSearchProvider()
  921. def tool_session_factory(
  922. validation_scope: ValidationScope,
  923. allowed_urls: set[str],
  924. validator_trace_id: str,
  925. ) -> ValidatorToolSession | None:
  926. limits_by_scope = {
  927. "evidence": ValidatorToolLimits(5, 10, 15),
  928. "hypothesis": ValidatorToolLimits(2, 4, 6),
  929. "root": ValidatorToolLimits(2, 5, 7),
  930. }
  931. limits = limits_by_scope.get(validation_scope)
  932. if limits is None:
  933. return None
  934. async def record_usage(
  935. tool_calls: int,
  936. chars: int,
  937. provider_cost_usd: float,
  938. ) -> None:
  939. await self.record_recursive_validation_usage(
  940. evaluated_trace_id,
  941. tool_calls=tool_calls,
  942. material_chars_count=chars,
  943. provider_cost_usd=provider_cost_usd,
  944. )
  945. session_kwargs: Dict[str, Any] = {}
  946. if self.validator_page_fetcher is not None:
  947. session_kwargs["page_fetcher"] = self.validator_page_fetcher
  948. return ValidatorToolSession(
  949. provider=provider,
  950. allowed_urls=allowed_urls,
  951. limits=limits,
  952. usage_recorder=record_usage,
  953. **session_kwargs,
  954. )
  955. validator = LLMValidator(
  956. llm_call=validator_llm_call,
  957. trace_store=self.trace_store,
  958. policy=policy,
  959. tool_session_factory=tool_session_factory,
  960. cancel_check=self.is_cancel_requested,
  961. trace_register=self.register_recursive_child,
  962. trace_release=self.release_recursive_trace,
  963. )
  964. try:
  965. async def persist_scope(result: ScopeValidationResult) -> None:
  966. if candidate_ref is not None:
  967. by_scope = {
  968. item.get("scope"): item
  969. for item in validation_cache.get("scope_results", [])
  970. if isinstance(item, dict)
  971. }
  972. by_scope[result.scope] = result.model_dump(mode="json")
  973. validation_cache["scope_results"] = [
  974. by_scope[item]
  975. for item in plan.effective_scopes
  976. if item in by_scope
  977. ]
  978. await self.candidate_service.update_validation_checkpoint(
  979. evaluated_trace_id,
  980. candidate_ref,
  981. plan.plan_hash,
  982. scope_results=tuple(validation_cache["scope_results"]),
  983. )
  984. return
  985. assert self.task_protocol_service is not None
  986. def persist_trace_scope(_trace, fresh_state):
  987. cache = fresh_state.get("task_report_validation")
  988. if (
  989. not isinstance(cache, dict)
  990. or cache.get("plan_hash") != plan.plan_hash
  991. ):
  992. raise ValueError(
  993. "Validation cache changed while scopes were running"
  994. )
  995. by_scope = {
  996. item.get("scope"): item
  997. for item in cache.get("scope_results", [])
  998. if isinstance(item, dict)
  999. }
  1000. by_scope[result.scope] = result.model_dump(mode="json")
  1001. cache["scope_results"] = [
  1002. by_scope[item]
  1003. for item in plan.effective_scopes
  1004. if item in by_scope
  1005. ]
  1006. await self.task_protocol_service.mutate_state(
  1007. evaluated_trace_id,
  1008. persist_trace_scope,
  1009. )
  1010. run = await validator.validate_plan(
  1011. evaluated_trace=evaluated,
  1012. trajectory=trajectory,
  1013. plan=plan,
  1014. root_task_anchor=root_anchor,
  1015. task_brief=task_brief,
  1016. task_report=task_report,
  1017. task_progress=task_progress,
  1018. candidate_output=candidate_output,
  1019. materials=materials,
  1020. material_issues=material_issues,
  1021. model_by_scope=model_by_scope,
  1022. source_urls=source_urls,
  1023. resume_scope_results=resume_scope_results,
  1024. on_scope_result=persist_scope,
  1025. fixed_checks=fixed_checks,
  1026. fixed_scope_errors=fixed_scope_errors,
  1027. )
  1028. if candidate_ref is not None:
  1029. from cyber_agent.application.quality import CandidateValidationRecord
  1030. await self.candidate_service.record_validation(
  1031. evaluated_trace_id,
  1032. CandidateValidationRecord(
  1033. candidate_ref=candidate_ref,
  1034. plan_hash=plan.plan_hash,
  1035. validation_result=run.result.model_dump(mode="json"),
  1036. validated_at_sequence=plan.evaluated_head_sequence,
  1037. ),
  1038. )
  1039. return run
  1040. assert self.task_protocol_service is not None
  1041. def persist_aggregate(_trace, fresh_state):
  1042. cache = fresh_state.get("task_report_validation")
  1043. if (
  1044. not isinstance(cache, dict)
  1045. or cache.get("plan_hash") != plan.plan_hash
  1046. ):
  1047. raise ValueError("Validation cache changed before aggregation")
  1048. cache["aggregate_result"] = run.result.model_dump(mode="json")
  1049. cache["scope_results"] = [
  1050. item.model_dump(mode="json")
  1051. for item in run.result.scope_results
  1052. ]
  1053. await self.task_protocol_service.mutate_state(
  1054. evaluated_trace_id,
  1055. persist_aggregate,
  1056. )
  1057. if self.event_service is not None:
  1058. await self.event_service.emit_after_commit(
  1059. source_trace_id=evaluated_trace_id,
  1060. event_type="validation.completed",
  1061. event_key=(
  1062. f"validation.completed:trace:{evaluated_trace_id}:"
  1063. f"{plan.plan_hash}"
  1064. ),
  1065. effective_at_sequence=plan.evaluated_head_sequence,
  1066. payload={
  1067. "subject_type": "trace",
  1068. "validation_result": run.result.model_dump(mode="json"),
  1069. },
  1070. )
  1071. return run
  1072. finally:
  1073. if lineage_event is not None:
  1074. self.release_recursive_trace(evaluated_trace_id, lineage_event)
  1075. async def _run_quality_checks(
  1076. self,
  1077. subject: Any,
  1078. materials: tuple[ValidationMaterial, ...],
  1079. rules: tuple[Any, ...],
  1080. usage_operation_prefix: str,
  1081. ) -> tuple[dict[str, ValidationCheck], dict[ValidationScope, str]]:
  1082. checks: dict[str, ValidationCheck] = {}
  1083. errors: dict[ValidationScope, str] = {}
  1084. for scope in dict.fromkeys(rule.scope for rule in rules):
  1085. scoped_rules = tuple(rule for rule in rules if rule.scope == scope)
  1086. scoped_checks, scoped_errors = await self._run_quality_check_batch(
  1087. subject,
  1088. materials,
  1089. scoped_rules,
  1090. usage_operation_id=f"{usage_operation_prefix}:quality:{scope}",
  1091. )
  1092. checks.update(scoped_checks)
  1093. errors.update(scoped_errors)
  1094. return checks, errors
  1095. async def _run_quality_check_batch(
  1096. self,
  1097. subject: Any,
  1098. materials: tuple[ValidationMaterial, ...],
  1099. rules: tuple[Any, ...],
  1100. usage_operation_id: str,
  1101. ) -> tuple[dict[str, ValidationCheck], dict[ValidationScope, str]]:
  1102. """Execute one frozen quality batch and reject provider-shaped plans."""
  1103. from cyber_agent.application.quality import (
  1104. QualityCheckInput,
  1105. QualityCheckOutcome,
  1106. )
  1107. provider = self.application_binding.services.quality_provider
  1108. check_ids = {rule.rule_id: f"quality.{rule.rule_id}" for rule in rules}
  1109. def provider_error(reason: str):
  1110. return (
  1111. {
  1112. check_id: ValidationCheck(
  1113. check_id=check_id,
  1114. status="unknown",
  1115. issue=reason,
  1116. )
  1117. for check_id in check_ids.values()
  1118. },
  1119. {rule.scope: reason for rule in rules},
  1120. )
  1121. if provider is None:
  1122. return provider_error("QualityCheckProvider is unavailable")
  1123. if not materials:
  1124. return provider_error("QualityCheckProvider has no authorized material")
  1125. request = QualityCheckInput(
  1126. subject=subject,
  1127. rules=rules,
  1128. materials=materials,
  1129. )
  1130. try:
  1131. # Reserve/record the idempotent quality call before crossing the
  1132. # provider boundary. Exhausted budgets therefore fail closed with
  1133. # zero provider side effects; provider errors still consume the
  1134. # attempted call exactly once.
  1135. await self.record_recursive_validation_usage(
  1136. subject.trace_id,
  1137. tool_calls=len(rules),
  1138. operation_id=usage_operation_id,
  1139. )
  1140. except Exception as exc:
  1141. return provider_error(f"Quality validation budget failed: {exc}")
  1142. try:
  1143. raw = await asyncio.wait_for(
  1144. provider.check(request),
  1145. timeout=max(rule.timeout_seconds for rule in rules),
  1146. )
  1147. outcomes = [QualityCheckOutcome.model_validate(item) for item in raw]
  1148. except Exception as exc:
  1149. return provider_error(f"QualityCheckProvider failed: {exc}")
  1150. returned = [(item.rule_id, item.rule_version) for item in outcomes]
  1151. expected = [(item.rule_id, item.version) for item in rules]
  1152. if len(returned) != len(set(returned)) or set(returned) != set(expected):
  1153. extras = sorted(set(returned) - set(expected))
  1154. missing = sorted(set(expected) - set(returned))
  1155. return provider_error(
  1156. "QualityCheckProvider results do not match the frozen rules: "
  1157. f"extras={extras}, missing={missing}"
  1158. )
  1159. by_rule = {item.rule_id: item for item in outcomes}
  1160. checks: dict[str, ValidationCheck] = {}
  1161. errors: dict[ValidationScope, str] = {}
  1162. for rule in rules:
  1163. outcome = by_rule[rule.rule_id]
  1164. check_id = check_ids[rule.rule_id]
  1165. checks[check_id] = ValidationCheck(
  1166. check_id=check_id,
  1167. status=("unknown" if outcome.status == "error" else outcome.status),
  1168. evidence_refs=list(outcome.evidence_refs),
  1169. issue=outcome.issue,
  1170. )
  1171. if outcome.status == "error":
  1172. errors[rule.scope] = outcome.issue or "Quality check failed"
  1173. return checks, errors
  1174. async def dream(
  1175. self,
  1176. memory_config: MemoryConfig,
  1177. *,
  1178. uid: Optional[str],
  1179. agent_type: str,
  1180. reflect_model: str = "gpt-4o-mini",
  1181. dream_model: str = "gpt-4o",
  1182. ) -> "DreamReport":
  1183. """执行 dream(整理长期记忆)——外部调度入口。
  1184. Agent 主动调用走 dream 工具;外部调度(定时器、CLI)走这个方法。
  1185. Args:
  1186. memory_config: 记忆配置
  1187. uid/agent_type: 与 MemoryConfig 一起形成强制 Dream 身份边界
  1188. reflect_model: per-trace 反思模型
  1189. dream_model: 跨 trace 整合模型
  1190. """
  1191. from cyber_agent.core.dream import DreamScope, run_dream
  1192. if not self.trace_store or not self.llm_call:
  1193. raise RuntimeError("dream 需要 trace_store 和 llm_call 均已配置")
  1194. return await run_dream(
  1195. store=self.trace_store,
  1196. llm_call=self.llm_call,
  1197. memory_config=memory_config,
  1198. dream_scope=DreamScope(
  1199. uid=uid,
  1200. agent_type=agent_type,
  1201. memory_identity=compute_memory_identity(memory_config),
  1202. ),
  1203. reflect_model=reflect_model,
  1204. dream_model=dream_model,
  1205. )
  1206. async def run(
  1207. self,
  1208. messages: List[Dict],
  1209. config: Optional[RunConfig] = None,
  1210. inject_skills: Optional[List[str]] = None,
  1211. skill_recency_threshold: int = 10,
  1212. ) -> AsyncIterator[Union[Trace, Message]]:
  1213. """
  1214. Agent 模式执行(核心方法)
  1215. Args:
  1216. messages: OpenAI SDK 格式的输入消息
  1217. 新建: 初始任务消息 [{"role": "user", "content": "..."}]
  1218. 续跑: 追加的新消息
  1219. 回溯: 在插入点之后追加的消息
  1220. config: 运行配置
  1221. inject_skills: 本次调用需要指定注入的 skill 列表(skill 名称)
  1222. skill_recency_threshold: 最近 N 条消息内有该 skill 就不重复注入
  1223. Yields:
  1224. Union[Trace, Message]: Trace 对象(状态变化)或 Message 对象(执行过程)
  1225. """
  1226. if not self.llm_call:
  1227. raise ValueError("llm_call function not provided")
  1228. config = config or RunConfig()
  1229. trace = None
  1230. run_cancel_event: Optional[asyncio.Event] = None
  1231. try:
  1232. # Phase 1: PREPARE TRACE
  1233. trace, goal_tree, sequence = await self._prepare_trace(messages, config)
  1234. # 子 Trace 可能已在排队阶段收到停止信号,不能覆盖既有 Event。
  1235. run_cancel_event = self._cancel_events.setdefault(
  1236. trace.trace_id,
  1237. asyncio.Event(),
  1238. )
  1239. if policy_from_context(trace.context).mode is AgentMode.RECURSIVE:
  1240. self._recursive_active_traces[trace.trace_id] = run_cancel_event
  1241. if trace.parent_trace_id:
  1242. self._active_children.setdefault(
  1243. trace.parent_trace_id,
  1244. set(),
  1245. ).add(trace.trace_id)
  1246. self._active_parents[trace.trace_id] = trace.parent_trace_id
  1247. yield trace
  1248. # 检查是否有未完成的侧分支(用于用户追加消息场景)
  1249. side_branch_ctx_for_build: Optional[SideBranchContext] = None
  1250. if trace.context.get("active_side_branch") and messages:
  1251. side_branch_data = trace.context["active_side_branch"]
  1252. # 创建侧分支上下文(用于标记用户追加的消息)
  1253. side_branch_ctx_for_build = SideBranchContext(
  1254. type=side_branch_data["type"],
  1255. branch_id=side_branch_data["branch_id"],
  1256. start_head_seq=side_branch_data["start_head_seq"],
  1257. start_sequence=side_branch_data["start_sequence"],
  1258. start_history_length=0,
  1259. start_iteration=side_branch_data.get("start_iteration", 0),
  1260. max_turns=side_branch_data.get("max_turns", config.side_branch_max_turns),
  1261. turns_used=side_branch_data.get("turns_used", 0),
  1262. )
  1263. # Phase 2: BUILD HISTORY
  1264. history, sequence, created_messages, head_seq = await self._build_history(
  1265. trace.trace_id, messages, goal_tree, config, sequence, side_branch_ctx_for_build
  1266. )
  1267. # History recovery may replay an idempotent protocol command and
  1268. # commit a newer context before the model loop starts. Keep the
  1269. # yielded Trace object aligned with that authoritative Store state.
  1270. if self.trace_store:
  1271. recovered_trace = await self.trace_store.get_trace(trace.trace_id)
  1272. if recovered_trace is not None:
  1273. trace.context = recovered_trace.context
  1274. trace.last_sequence = recovered_trace.last_sequence
  1275. # Update trace's head_sequence in memory
  1276. trace.head_sequence = head_seq
  1277. for msg in created_messages:
  1278. yield msg
  1279. # Phase 3: AGENT LOOP
  1280. async for event in self._agent_loop(
  1281. trace, history, goal_tree, config, sequence,
  1282. inject_skills=inject_skills,
  1283. skill_recency_threshold=skill_recency_threshold,
  1284. ):
  1285. yield event
  1286. except PendingToolApprovalRestored:
  1287. if trace and self.trace_store:
  1288. waiting_trace = await self.trace_store.get_trace(trace.trace_id)
  1289. if waiting_trace is not None:
  1290. yield waiting_trace
  1291. return
  1292. except asyncio.CancelledError:
  1293. if trace and config.approval_batch_id:
  1294. await asyncio.shield(
  1295. self._mark_approval_execution_unknown(trace.trace_id)
  1296. )
  1297. raise
  1298. except Exception as e:
  1299. self.log.error(f"Agent run failed: {e}")
  1300. # Preparation rejections (for example, attempting to resume an
  1301. # immutable Validator Trace) must not rewrite the existing record.
  1302. tid = trace.trace_id if trace else None
  1303. if self.trace_store and tid:
  1304. approval_unknown = (
  1305. await self._mark_approval_execution_unknown(tid)
  1306. if config.approval_batch_id
  1307. else False
  1308. )
  1309. # 读取当前 last_sequence 作为 head_sequence,确保续跑时能加载完整历史
  1310. current = await self.trace_store.get_trace(tid)
  1311. head_seq = current.last_sequence if current else None
  1312. updates: Dict[str, Any] = {
  1313. "status": "failed",
  1314. "head_sequence": head_seq,
  1315. "error_message": (
  1316. "Tool execution outcome is unknown; automatic retry was refused"
  1317. if approval_unknown
  1318. else str(e)
  1319. ),
  1320. "completed_at": datetime.now(),
  1321. }
  1322. if isinstance(e, ResourceBudgetExceeded):
  1323. current_context = dict(current.context if current else {})
  1324. current_context["termination_reason"] = (
  1325. f"budget_exhausted:{e.dimension}"
  1326. )
  1327. updates["context"] = current_context
  1328. await self.trace_store.update_trace(
  1329. tid,
  1330. **updates,
  1331. )
  1332. trace_obj = await self.trace_store.get_trace(tid)
  1333. if trace_obj:
  1334. yield trace_obj
  1335. raise
  1336. finally:
  1337. if trace and run_cancel_event is not None:
  1338. self.release_recursive_trace(trace.trace_id, run_cancel_event)
  1339. async def run_result(
  1340. self,
  1341. messages: List[Dict],
  1342. config: Optional[RunConfig] = None,
  1343. on_event: Optional[Callable] = None,
  1344. inject_skills: Optional[List[str]] = None,
  1345. ) -> Dict[str, Any]:
  1346. """
  1347. 结果模式 — 消费 run(),返回结构化结果。
  1348. 主要用于 agent/evaluate 工具内部。
  1349. Args:
  1350. on_event: 可选回调,每个 Trace/Message 事件触发一次,用于实时输出子 Agent 执行过程。
  1351. inject_skills: 本次调用需要指定注入的 skill 列表(透传给 run())。
  1352. """
  1353. last_assistant_text = ""
  1354. final_trace: Optional[Trace] = None
  1355. async for item in self.run(messages=messages, config=config, inject_skills=inject_skills):
  1356. if on_event:
  1357. on_event(item)
  1358. if isinstance(item, Message) and item.role == "assistant":
  1359. content = item.content
  1360. text = ""
  1361. if isinstance(content, dict):
  1362. text = content.get("text", "") or ""
  1363. elif isinstance(content, str):
  1364. text = content
  1365. if text and text.strip():
  1366. last_assistant_text = text
  1367. elif isinstance(item, Trace):
  1368. final_trace = item
  1369. config = config or RunConfig()
  1370. if not final_trace and config.trace_id and self.trace_store:
  1371. final_trace = await self.trace_store.get_trace(config.trace_id)
  1372. status = final_trace.status if final_trace else "unknown"
  1373. error = final_trace.error_message if final_trace else None
  1374. summary = last_assistant_text
  1375. stopped_recursively = bool(
  1376. final_trace
  1377. and status == "stopped"
  1378. and policy_from_context(final_trace.context).mode is AgentMode.RECURSIVE
  1379. )
  1380. if not summary and stopped_recursively:
  1381. summary = "Agent execution stopped."
  1382. elif not summary and status == "waiting_confirmation":
  1383. summary = "Agent is waiting for local tool approval."
  1384. elif not summary:
  1385. status = "failed"
  1386. error = error or "Agent 没有产生 assistant 文本结果"
  1387. # 获取保存的知识 ID
  1388. trace_id = final_trace.trace_id if final_trace else config.trace_id
  1389. saved_knowledge_ids = self._saved_knowledge_ids.get(trace_id, [])
  1390. return {
  1391. "status": status,
  1392. "summary": summary,
  1393. "trace_id": trace_id,
  1394. "error": error,
  1395. "saved_knowledge_ids": saved_knowledge_ids, # 新增:返回保存的知识 ID
  1396. "stats": {
  1397. "total_messages": final_trace.total_messages if final_trace else 0,
  1398. "total_tokens": final_trace.total_tokens if final_trace else 0,
  1399. "total_cost": final_trace.total_cost if final_trace else 0.0,
  1400. },
  1401. }
  1402. async def stop(self, trace_id: str) -> bool:
  1403. """
  1404. 停止运行中的 Trace
  1405. Trace API 定位实际 Runner 后调用本方法;Legacy 只停当前 Trace,
  1406. Recursive 由 ``request_stop`` 把信号传给当前进程内已登记的子树。
  1407. Returns:
  1408. True 如果成功发送停止信号,False 如果该 trace 不在运行中
  1409. """
  1410. return self.request_stop(trace_id)
  1411. def request_stop(self, trace_id: str) -> bool:
  1412. """同步设置停止信号,供 API 与 stdin 回调共用。
  1413. Recursive Trace 会沿进程内父子登记表向下遍历,不影响父级或兄弟分支。
  1414. """
  1415. if trace_id not in self._cancel_events:
  1416. return False
  1417. if trace_id not in self._recursive_active_traces:
  1418. self._cancel_events[trace_id].set()
  1419. return True
  1420. pending = [trace_id]
  1421. visited = set()
  1422. while pending:
  1423. current = pending.pop()
  1424. if current in visited:
  1425. continue
  1426. visited.add(current)
  1427. event = self._cancel_events.get(current)
  1428. if event:
  1429. event.set()
  1430. pending.extend(tuple(self._active_children.get(current, ())))
  1431. return True
  1432. def register_recursive_child(
  1433. self,
  1434. parent_trace_id: str,
  1435. child_trace_id: str,
  1436. ) -> asyncio.Event:
  1437. """登记已创建但可能仍在排队的 Recursive 直属孩子。
  1438. ``agent`` 工具预创建孩子后、Runner 启动 Validator 前调用,使父级停止能传递到后代。
  1439. """
  1440. event = self._cancel_events.setdefault(child_trace_id, asyncio.Event())
  1441. self._recursive_active_traces[child_trace_id] = event
  1442. self._active_children.setdefault(parent_trace_id, set()).add(child_trace_id)
  1443. self._active_parents[child_trace_id] = parent_trace_id
  1444. parent_event = self._cancel_events.get(parent_trace_id)
  1445. if parent_event and parent_event.is_set():
  1446. event.set()
  1447. return event
  1448. def is_cancel_requested(self, trace_id: str) -> bool:
  1449. event = self._cancel_events.get(trace_id)
  1450. return bool(event and event.is_set())
  1451. def unregister_recursive_trace(
  1452. self,
  1453. trace_id: str,
  1454. event: Optional[asyncio.Event] = None,
  1455. ) -> None:
  1456. """幂等清理运行登记;event 防止旧运行误删续跑状态。"""
  1457. current_event = self._recursive_active_traces.get(trace_id)
  1458. if event is not None and current_event is not event:
  1459. return
  1460. self._recursive_active_traces.pop(trace_id, None)
  1461. parent_id = self._active_parents.pop(trace_id, None)
  1462. if parent_id:
  1463. children = self._active_children.get(parent_id)
  1464. if children:
  1465. children.discard(trace_id)
  1466. if not children:
  1467. self._active_children.pop(parent_id, None)
  1468. if not self._active_children.get(trace_id):
  1469. self._active_children.pop(trace_id, None)
  1470. def release_recursive_trace(
  1471. self,
  1472. trace_id: str,
  1473. event: Optional[asyncio.Event] = None,
  1474. ) -> None:
  1475. """完成一次运行并按对象身份释放取消 Event 与父子登记。"""
  1476. current_event = self._cancel_events.get(trace_id)
  1477. if event is not None and current_event is not event:
  1478. return
  1479. self.unregister_recursive_trace(trace_id, event)
  1480. if self._cancel_events.get(trace_id) is current_event:
  1481. self._cancel_events.pop(trace_id, None)
  1482. async def _mark_trace_stopped(
  1483. self,
  1484. trace_id: str,
  1485. head_sequence: Optional[int],
  1486. ) -> Optional[Trace]:
  1487. if not self.trace_store:
  1488. return None
  1489. await self.trace_store.update_trace(
  1490. trace_id,
  1491. status="stopped",
  1492. head_sequence=head_sequence,
  1493. completed_at=datetime.now(),
  1494. )
  1495. try:
  1496. from cyber_agent.trace.websocket import broadcast_trace_status_changed
  1497. await broadcast_trace_status_changed(trace_id, "stopped")
  1498. except Exception:
  1499. pass
  1500. return await self.trace_store.get_trace(trace_id)
  1501. # ===== 单次调用(保留)=====
  1502. async def call(
  1503. self,
  1504. messages: List[Dict],
  1505. model: str = "gpt-4o",
  1506. tools: Optional[List[str]] = None,
  1507. uid: Optional[str] = None,
  1508. trace: bool = True,
  1509. **kwargs
  1510. ) -> CallResult:
  1511. """
  1512. 单次 LLM 调用(无 Agent Loop)
  1513. """
  1514. if not self.llm_call:
  1515. raise ValueError("llm_call function not provided")
  1516. trace_id = None
  1517. message_id = None
  1518. tool_schemas = self._get_tool_schemas(tools)
  1519. if trace and self.trace_store:
  1520. trace_obj = Trace.create(mode="call", uid=uid, model=model, tools=tool_schemas, llm_params=kwargs)
  1521. trace_id = await self.trace_store.create_trace(trace_obj)
  1522. result = await self.llm_call(messages=messages, model=model, tools=tool_schemas, **kwargs)
  1523. if trace and self.trace_store and trace_id:
  1524. msg = Message.create(
  1525. trace_id=trace_id, role="assistant", sequence=1, goal_id=None,
  1526. content={"text": result.get("content", ""), "tool_calls": result.get("tool_calls")},
  1527. prompt_tokens=result.get("prompt_tokens", 0),
  1528. completion_tokens=result.get("completion_tokens", 0),
  1529. finish_reason=result.get("finish_reason"),
  1530. cost=result.get("cost", 0),
  1531. )
  1532. message_id = await self.trace_store.add_message(msg)
  1533. await self.trace_store.update_trace(trace_id, status="completed", completed_at=datetime.now())
  1534. return CallResult(
  1535. reply=result.get("content", ""),
  1536. tool_calls=result.get("tool_calls"),
  1537. trace_id=trace_id,
  1538. step_id=message_id,
  1539. tokens={"prompt": result.get("prompt_tokens", 0), "completion": result.get("completion_tokens", 0)},
  1540. cost=result.get("cost", 0)
  1541. )
  1542. # ===== Phase 1: PREPARE TRACE =====
  1543. async def _prepare_trace(
  1544. self,
  1545. messages: List[Dict],
  1546. config: RunConfig,
  1547. ) -> Tuple[Trace, Optional[GoalTree], int]:
  1548. """
  1549. 准备 Trace:为 ``run`` 选择新建、续跑或回溯路径。
  1550. 在 Agent 主循环前调用,并在任何 Trace 操作前校验已废弃的配置项。
  1551. Returns:
  1552. (trace, goal_tree, next_sequence)
  1553. """
  1554. assert_removed_config_absent()
  1555. if self.application_binding is not None and any(
  1556. message.get("role") == "system" for message in messages
  1557. ):
  1558. raise ValueError(
  1559. "Application runs do not allow caller-provided system messages"
  1560. )
  1561. if config.trace_id:
  1562. if self.trace_store and hasattr(
  1563. self.trace_store,
  1564. "get_tool_approval_batch",
  1565. ):
  1566. batch = await self.trace_store.get_tool_approval_batch(
  1567. config.trace_id
  1568. )
  1569. if (
  1570. batch is not None
  1571. and batch.status == "executing"
  1572. and await self._recover_candidate_approval_if_durable(
  1573. config.trace_id,
  1574. batch,
  1575. )
  1576. ):
  1577. batch = await self.trace_store.get_tool_approval_batch(
  1578. config.trace_id
  1579. )
  1580. if (
  1581. batch is not None
  1582. and batch.status == "recoverable_candidate_command"
  1583. and (
  1584. messages
  1585. or config.after_sequence is not None
  1586. or config.force_side_branch
  1587. )
  1588. ):
  1589. raise ValueError(
  1590. "recoverable_candidate_command_must_resume_first"
  1591. )
  1592. return await self._prepare_existing_trace(config)
  1593. else:
  1594. return await self._prepare_new_trace(messages, config)
  1595. @staticmethod
  1596. def _application_ref_dict(value: Any) -> dict[str, Any] | None:
  1597. if value is None:
  1598. return None
  1599. if hasattr(value, "model_dump"):
  1600. return value.model_dump(mode="json")
  1601. return dict(value) if isinstance(value, dict) else None
  1602. def _validate_application_config(self, config: RunConfig) -> None:
  1603. """Reject a new application RunConfig that diverges from its Binding."""
  1604. binding = self.application_binding
  1605. if binding is None:
  1606. raise ValueError("Application binding is unavailable")
  1607. expected_ref = binding.application_ref.model_dump(mode="json")
  1608. if self._application_ref_dict(config.application_ref) != expected_ref:
  1609. raise ValueError("RunConfig ApplicationRef does not match Runner binding")
  1610. if not config.role_id:
  1611. raise ValueError("Application role_id is required")
  1612. role = binding.role(config.role_id)
  1613. if config.role_hash != role.role_hash:
  1614. raise ValueError("RunConfig role hash does not match Runner binding")
  1615. if (
  1616. config.model != role.role.model
  1617. or config.temperature != role.role.temperature
  1618. or config.extra_llm_params != role.role.model_parameters
  1619. or not set(config.tools or []).issubset(set(role.tool_names))
  1620. or config.system_prompt != role.system_prompt
  1621. or config.skills != []
  1622. ):
  1623. raise ValueError("RunConfig behavior does not match the bound application role")
  1624. limits = dict(config.effective_run_limits)
  1625. if not limits:
  1626. raise ValueError("Application effective_run_limits are required")
  1627. allowed_limits = role.effective_limits.model_dump(mode="json")
  1628. for name, allowed in allowed_limits.items():
  1629. value = limits.get(name)
  1630. if value is None or value > allowed:
  1631. raise ValueError(
  1632. f"Application run limit exceeds the bound role: {name}"
  1633. )
  1634. if (
  1635. config.max_iterations != limits["max_iterations"]
  1636. or config.max_parallel_children != limits["max_parallel_children"]
  1637. ):
  1638. raise ValueError("RunConfig limits do not match effective_run_limits")
  1639. def _validate_application_snapshot(
  1640. self,
  1641. snapshot: RunConfigSnapshotV1 | RunConfigSnapshotV2,
  1642. trace: Trace,
  1643. ) -> None:
  1644. """Perform the Runner-side binding gate before any resume mutation."""
  1645. if isinstance(snapshot, RunConfigSnapshotV1) and not isinstance(
  1646. snapshot,
  1647. RunConfigSnapshotV2,
  1648. ):
  1649. if self.application_binding is not None:
  1650. raise ValueError("Application-bound Runner cannot resume a V1 Trace")
  1651. return
  1652. if self.application_binding is None:
  1653. raise ValueError(
  1654. "Application Trace requires an ApplicationRuntime-bound Runner"
  1655. )
  1656. expected_ref = self.application_binding.application_ref.model_dump(mode="json")
  1657. if snapshot.application_ref != expected_ref:
  1658. raise ValueError("ApplicationRef does not match Runner binding")
  1659. role = self.application_binding.role(snapshot.role_id)
  1660. if snapshot.role_hash != role.role_hash:
  1661. raise ValueError("Application role hash does not match Runner binding")
  1662. if (
  1663. trace.context.get("application_ref") != snapshot.application_ref
  1664. or trace.context.get("application_role_id") != snapshot.role_id
  1665. or trace.context.get("application_role_hash") != snapshot.role_hash
  1666. or trace.context.get("effective_run_limits")
  1667. != snapshot.effective_run_limits
  1668. ):
  1669. raise ValueError("Application snapshot does not match Trace context")
  1670. restored = RunConfig()
  1671. restored.apply_snapshot(snapshot)
  1672. restored.system_prompt = role.system_prompt
  1673. restored.skills = []
  1674. self._validate_application_config(restored)
  1675. async def _prepare_new_trace(
  1676. self,
  1677. messages: List[Dict],
  1678. config: RunConfig,
  1679. ) -> Tuple[Trace, Optional[GoalTree], int]:
  1680. """创建并持久化一个新根 Trace。
  1681. ``run`` 首次执行时调用;Recursive 会在此固化根任务锚点和树级预算。
  1682. """
  1683. if self.application_binding is not None:
  1684. self._validate_application_config(config)
  1685. elif config.application_ref is not None:
  1686. raise ValueError(
  1687. "Application runs require an ApplicationRuntime-bound Runner"
  1688. )
  1689. # 在任何标题生成/LLM 调用前完成模式校验。
  1690. policy = policy_from_environment(
  1691. recursive_revision=CURRENT_RECURSIVE_REVISION,
  1692. )
  1693. if policy.mode is AgentMode.RECURSIVE:
  1694. validate_recursive_child_execution(
  1695. config.child_execution_mode,
  1696. config.max_parallel_children,
  1697. )
  1698. if config.root_task_anchor is None:
  1699. raise ValueError(
  1700. "New Recursive root traces require root_task_anchor"
  1701. )
  1702. try:
  1703. root_task_anchor = normalize_root_task_anchor(
  1704. config.root_task_anchor
  1705. )
  1706. except ContextPolicyError as exc:
  1707. raise ValueError(str(exc)) from exc
  1708. deployment_budget = ResourceBudget.from_environment()
  1709. if self.application_binding is not None:
  1710. limits = config.effective_run_limits
  1711. budget = ResourceBudget(
  1712. enabled=deployment_budget.enabled,
  1713. max_total_agents=int(limits["max_total_agents"]),
  1714. max_llm_calls=int(limits["max_llm_calls"]),
  1715. max_total_tokens=int(limits["max_total_tokens"]),
  1716. max_total_cost_usd=float(limits["max_total_cost_usd"]),
  1717. max_duration_seconds=int(limits["max_duration_seconds"]),
  1718. reserved_final_calls=min(
  1719. deployment_budget.reserved_final_calls,
  1720. int(limits["max_llm_calls"]) - 1,
  1721. ),
  1722. max_validation_tool_calls=int(
  1723. limits["max_validation_tool_calls"]
  1724. ),
  1725. max_validation_material_chars=int(
  1726. limits["max_validation_material_chars"]
  1727. ),
  1728. )
  1729. else:
  1730. budget = deployment_budget
  1731. validator_settings = ValidatorSettings.from_environment()
  1732. trace_id = str(uuid.uuid4())
  1733. # 生成任务名称
  1734. task_name = config.name or (
  1735. self._fallback_task_name(messages)
  1736. if policy.mode is AgentMode.RECURSIVE
  1737. else await self._generate_task_name(messages)
  1738. )
  1739. # 准备工具 Schema
  1740. tool_schemas = self._get_tool_schemas(config.tools, config.tool_groups, config.exclude_tools)
  1741. trace_context = apply_policy_to_context(config.context, policy)
  1742. trace_context.setdefault("agent_depth", 0)
  1743. trace_context.setdefault("root_trace_id", trace_id)
  1744. memory_identity = (
  1745. compute_memory_identity(config.memory) if config.memory else None
  1746. )
  1747. if memory_identity is not None:
  1748. trace_context[MEMORY_IDENTITY_CONTEXT_KEY] = memory_identity
  1749. if self.application_binding is not None:
  1750. run_snapshot = RunConfigSnapshotV2.from_run_config(
  1751. config,
  1752. memory_identity=memory_identity,
  1753. )
  1754. trace_context.update({
  1755. "application_ref": run_snapshot.application_ref,
  1756. "application_role_id": run_snapshot.role_id,
  1757. "application_role_hash": run_snapshot.role_hash,
  1758. "effective_run_limits": run_snapshot.effective_run_limits,
  1759. })
  1760. else:
  1761. run_snapshot = RunConfigSnapshotV1.from_run_config(
  1762. config,
  1763. memory_identity=memory_identity,
  1764. )
  1765. persist_run_config_snapshot(trace_context, run_snapshot)
  1766. if policy.requires_task_protocol:
  1767. persist_root_task_anchor(trace_context, root_task_anchor)
  1768. persist_validation_policy(
  1769. trace_context,
  1770. self.validation_policy,
  1771. validator_settings,
  1772. )
  1773. trace_context[RESOURCE_BUDGET_CONTEXT_KEY] = budget.to_dict()
  1774. trace_context["task_protocol"] = new_task_protocol()
  1775. state = ensure_task_protocol(trace_context)
  1776. if policy.requires_task_progress:
  1777. initialize_task_progress(
  1778. state,
  1779. root_task_anchor_hash=trace_context.get(
  1780. "root_task_anchor_hash"
  1781. ),
  1782. )
  1783. replace_context_access(
  1784. trace_context,
  1785. [],
  1786. root_task_anchor=root_task_anchor,
  1787. task_brief=state.get("task_brief"),
  1788. )
  1789. if self.application_binding is not None and self.context_provider is not None:
  1790. from cyber_agent.application.context import load_application_context
  1791. from cyber_agent.application.ports import ContextRequest
  1792. await load_application_context(
  1793. self.application_binding,
  1794. trace_context,
  1795. ContextRequest(
  1796. application_ref=self.application_binding.application_ref,
  1797. root_trace_id=trace_id,
  1798. trace_id=trace_id,
  1799. uid=config.uid,
  1800. role_id=config.role_id,
  1801. task_brief=None,
  1802. task_brief_revision=0,
  1803. ),
  1804. root_task_anchor=root_task_anchor,
  1805. task_brief=None,
  1806. granted_at_sequence=0,
  1807. )
  1808. trace_obj = Trace(
  1809. trace_id=trace_id,
  1810. mode="agent",
  1811. task=task_name,
  1812. agent_type=config.agent_type,
  1813. parent_trace_id=config.parent_trace_id,
  1814. parent_goal_id=config.parent_goal_id,
  1815. uid=config.uid,
  1816. model=config.model,
  1817. tools=tool_schemas,
  1818. llm_params={"temperature": config.temperature, **config.extra_llm_params},
  1819. context=trace_context,
  1820. status="running",
  1821. )
  1822. goal_tree = self.goal_tree or GoalTree(mission=task_name)
  1823. if self.trace_store:
  1824. await self.trace_store.create_trace(trace_obj)
  1825. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  1826. assert self.resource_budget is not None
  1827. if policy.mode is AgentMode.RECURSIVE:
  1828. await self.resource_budget.initialize(
  1829. trace_id,
  1830. budget,
  1831. initial_agents=1,
  1832. )
  1833. return trace_obj, goal_tree, 1
  1834. async def _prepare_existing_trace(
  1835. self,
  1836. config: RunConfig,
  1837. ) -> Tuple[Trace, Optional[GoalTree], int]:
  1838. """加载已有 Trace,决定续跑或回溯。
  1839. ``run`` 携带 ``trace_id`` 时调用;Recursive 只信任持久化模式、预算和协议状态。
  1840. """
  1841. if not self.trace_store:
  1842. raise ValueError("trace_store required for continue/rewind")
  1843. trace_obj = await self.trace_store.get_trace(config.trace_id)
  1844. if not trace_obj:
  1845. raise ValueError(f"Trace not found: {config.trace_id}")
  1846. if (
  1847. trace_obj.agent_type == "validator"
  1848. or trace_obj.context.get("created_by_tool") == "validator"
  1849. ):
  1850. raise ValueError(
  1851. "Validator traces cannot be continued or rewound"
  1852. )
  1853. require_mutable_trace_policy(trace_obj.context)
  1854. # Resume/rewind behavior is always recovered from the immutable snapshot.
  1855. # Old Recursive traces cannot be reconstructed safely; Legacy traces get
  1856. # one explicitly-marked, conservative inferred snapshot for compatibility.
  1857. if RUN_CONFIG_SNAPSHOT_CONTEXT_KEY in trace_obj.context:
  1858. try:
  1859. snapshot = load_run_config_snapshot(trace_obj.context)
  1860. except RunConfigSnapshotError as exc:
  1861. raise ValueError(str(exc)) from exc
  1862. else:
  1863. existing_policy = policy_from_context(trace_obj.context)
  1864. if existing_policy.mode is AgentMode.RECURSIVE:
  1865. raise ValueError(
  1866. "This Recursive trace predates RunConfig snapshots; create a new trace"
  1867. )
  1868. inferred = RunConfig(
  1869. model=trace_obj.model or "gpt-4o",
  1870. temperature=float((trace_obj.llm_params or {}).get("temperature", 0.3)),
  1871. tools=[
  1872. item.get("function", {}).get("name")
  1873. for item in (trace_obj.tools or [])
  1874. if item.get("function", {}).get("name")
  1875. ],
  1876. tool_groups=None,
  1877. agent_type=trace_obj.agent_type or "default",
  1878. uid=trace_obj.uid,
  1879. extra_llm_params={
  1880. key: value
  1881. for key, value in (trace_obj.llm_params or {}).items()
  1882. if key != "temperature"
  1883. },
  1884. context={
  1885. "project_name": trace_obj.context.get("project_name")
  1886. } if trace_obj.context.get("project_name") else {},
  1887. )
  1888. snapshot = RunConfigSnapshotV1.from_run_config(
  1889. inferred,
  1890. memory_identity=None,
  1891. legacy_inferred=True,
  1892. )
  1893. persist_run_config_snapshot(trace_obj.context, snapshot)
  1894. await self.trace_store.update_trace(
  1895. trace_obj.trace_id,
  1896. context=trace_obj.context,
  1897. )
  1898. if snapshot.uid != trace_obj.uid or snapshot.agent_type != (trace_obj.agent_type or "default"):
  1899. raise ValueError("run config snapshot identity does not match Trace metadata")
  1900. self._validate_application_snapshot(snapshot, trace_obj)
  1901. config.apply_snapshot(snapshot)
  1902. if isinstance(snapshot, RunConfigSnapshotV2):
  1903. role = self.application_binding.role(snapshot.role_id)
  1904. config.system_prompt = role.system_prompt
  1905. config.skills = []
  1906. if (
  1907. config.approval_batch_id is None
  1908. and hasattr(self.trace_store, "get_tool_approval_batch")
  1909. ):
  1910. approval_batch = await self.trace_store.get_tool_approval_batch(
  1911. trace_obj.trace_id
  1912. )
  1913. if (
  1914. approval_batch is not None
  1915. and approval_batch.status == "recoverable_candidate_command"
  1916. ):
  1917. self._validate_recoverable_candidate_approval(approval_batch)
  1918. config.approval_batch_id = approval_batch.batch_id
  1919. persisted_memory_identity = trace_obj.context.get(
  1920. MEMORY_IDENTITY_CONTEXT_KEY
  1921. )
  1922. if persisted_memory_identity != snapshot.memory_identity:
  1923. raise ValueError(
  1924. "run config snapshot memory identity does not match Trace context"
  1925. )
  1926. if config.memory is not None and (
  1927. compute_memory_identity(config.memory) != snapshot.memory_identity
  1928. ):
  1929. raise ValueError(
  1930. "restored MemoryConfig does not match the persisted memory identity"
  1931. )
  1932. # Historical traces predate AGENT_MODE. They resume in safe Legacy mode
  1933. # and the choice is persisted immediately; environment changes never
  1934. # mutate an existing tree.
  1935. if AGENT_MODE_CONTEXT_KEY not in trace_obj.context:
  1936. legacy_policy = policy_from_context(None)
  1937. trace_obj.context = apply_policy_to_context(trace_obj.context, legacy_policy)
  1938. await self.trace_store.update_trace(
  1939. config.trace_id,
  1940. context=trace_obj.context,
  1941. )
  1942. else:
  1943. policy = policy_from_context(trace_obj.context)
  1944. if policy.mode is AgentMode.RECURSIVE:
  1945. validate_recursive_child_execution(
  1946. config.child_execution_mode,
  1947. config.max_parallel_children,
  1948. )
  1949. if policy.requires_task_protocol:
  1950. root_trace_id = trace_obj.context.get("root_trace_id")
  1951. root = (
  1952. trace_obj
  1953. if root_trace_id == trace_obj.trace_id
  1954. else await self.trace_store.get_trace(root_trace_id)
  1955. )
  1956. if not root:
  1957. raise ValueError(
  1958. f"Recursive root Trace not found: {root_trace_id}"
  1959. )
  1960. try:
  1961. require_matching_root_task_anchor(
  1962. root.context,
  1963. trace_obj.context,
  1964. )
  1965. require_validation_policy(root.context)
  1966. except ContextPolicyError as exc:
  1967. raise ValueError(str(exc)) from exc
  1968. except ValueError as exc:
  1969. raise ValueError(str(exc)) from exc
  1970. if RESOURCE_BUDGET_CONTEXT_KEY not in root.context:
  1971. raise ValueError(
  1972. "This experimental Recursive trace predates tree resource "
  1973. "budgets; create a new trace"
  1974. )
  1975. ResourceBudget.from_dict(
  1976. root.context[RESOURCE_BUDGET_CONTEXT_KEY]
  1977. )
  1978. if root_trace_id == trace_obj.trace_id:
  1979. state = ensure_task_protocol(trace_obj.context)
  1980. if state["root_validation_attempts"] >= 2:
  1981. raise ValueError(
  1982. "Root task already used its two independent "
  1983. "validation attempts; create a new trace"
  1984. )
  1985. if policy.requires_task_progress:
  1986. assert self.task_protocol_service is not None
  1987. async with self.task_protocol_service.locked_trace(
  1988. trace_obj.trace_id
  1989. ) as fresh_trace:
  1990. state = ensure_task_protocol(fresh_trace.context)
  1991. had_report = state.get("task_report") is not None
  1992. report_progress_revision = state.get(
  1993. "task_report_progress_revision"
  1994. )
  1995. if had_report and report_progress_revision is None:
  1996. raise ValueError(
  1997. "TaskReport is missing its TaskProgress revision binding"
  1998. )
  1999. previous_head = state.get(
  2000. "task_progress_head_revision"
  2001. )
  2002. rewind_task_progress(
  2003. state,
  2004. fresh_trace.last_sequence,
  2005. )
  2006. if (
  2007. had_report
  2008. and state.get("task_report_progress_revision") is None
  2009. ):
  2010. raise ValueError(
  2011. "TaskReport references TaskProgress outside the "
  2012. "current revision ancestry"
  2013. )
  2014. if (
  2015. state.get("task_progress_head_revision")
  2016. != previous_head
  2017. ):
  2018. await self.trace_store.update_trace(
  2019. fresh_trace.trace_id,
  2020. context=fresh_trace.context,
  2021. )
  2022. trace_obj = fresh_trace
  2023. assert self.resource_budget is not None
  2024. await self.resource_budget.get_usage(root.trace_id)
  2025. goal_tree = await self.trace_store.get_goal_tree(config.trace_id)
  2026. if goal_tree is None:
  2027. # 防御性兜底:trace 存在但 goal.json 丢失时,创建空树
  2028. goal_tree = GoalTree(mission=trace_obj.task or "Agent task")
  2029. await self.trace_store.update_goal_tree(config.trace_id, goal_tree)
  2030. # 自动判断行为:after_sequence 为 None 或 == head → 续跑;< head → 回溯
  2031. after_seq = config.after_sequence
  2032. # 如果 after_seq > head_sequence,说明 generator 被强制关闭时 store 的
  2033. # head_sequence 未来得及更新(仍停在 Phase 2 写入的初始值)。
  2034. # 用 last_sequence 修正 head_sequence,确保续跑时能看到完整历史。
  2035. if after_seq is not None and after_seq > trace_obj.head_sequence:
  2036. trace_obj.head_sequence = trace_obj.last_sequence
  2037. await self.trace_store.update_trace(
  2038. config.trace_id, head_sequence=trace_obj.head_sequence
  2039. )
  2040. if after_seq is not None and after_seq < trace_obj.head_sequence:
  2041. # 回溯模式
  2042. sequence = await self._rewind(config.trace_id, after_seq, goal_tree)
  2043. else:
  2044. # 续跑模式:从 last_sequence + 1 开始
  2045. sequence = trace_obj.last_sequence + 1
  2046. # 状态置为 running
  2047. await self.trace_store.update_trace(
  2048. config.trace_id,
  2049. status="running",
  2050. completed_at=None,
  2051. )
  2052. trace_obj.status = "running"
  2053. # 广播状态变化给前端
  2054. try:
  2055. from cyber_agent.trace.websocket import broadcast_trace_status_changed
  2056. await broadcast_trace_status_changed(config.trace_id, "running")
  2057. except Exception:
  2058. pass
  2059. return trace_obj, goal_tree, sequence
  2060. # ===== Phase 2: BUILD HISTORY =====
  2061. async def _build_history(
  2062. self,
  2063. trace_id: str,
  2064. new_messages: List[Dict],
  2065. goal_tree: Optional[GoalTree],
  2066. config: RunConfig,
  2067. sequence: int,
  2068. side_branch_ctx: Optional[SideBranchContext] = None,
  2069. ) -> Tuple[List[Dict], int, List[Message], int]:
  2070. """
  2071. 构建完整的 LLM 消息历史
  2072. 1. 从 head_sequence 沿 parent chain 加载主路径消息(续跑/回溯场景)
  2073. 2. 构建 system prompt(新建时注入 skills)
  2074. 3. 新建时:在第一条 user message 末尾注入当前经验
  2075. 4. 追加 input messages(设置 parent_sequence 链接到当前 head)
  2076. 5. 如果在侧分支中,追加的消息自动标记为侧分支消息
  2077. Returns:
  2078. (history, next_sequence, created_messages, head_sequence)
  2079. created_messages: 本次新创建并持久化的 Message 列表,供 run() yield 给调用方
  2080. head_sequence: 当前主路径头节点的 sequence
  2081. """
  2082. history: List[Dict] = []
  2083. created_messages: List[Message] = []
  2084. head_seq: Optional[int] = None # 当前主路径的头节点 sequence
  2085. # 1. 加载已有 messages(通过主路径遍历)
  2086. if config.trace_id and self.trace_store:
  2087. trace_obj = await self.trace_store.get_trace(trace_id)
  2088. if trace_obj and trace_obj.head_sequence > 0:
  2089. main_path = await self.trace_store.get_main_path_messages(
  2090. trace_id, trace_obj.head_sequence
  2091. )
  2092. # An approved pending batch deliberately has orphaned calls;
  2093. # they are executed before the next model turn.
  2094. if not config.approval_batch_id:
  2095. main_path, sequence = await self._heal_orphaned_tool_calls(
  2096. main_path,
  2097. trace_obj,
  2098. goal_tree,
  2099. config,
  2100. sequence,
  2101. )
  2102. history = [msg.to_llm_dict() for msg in main_path]
  2103. if main_path:
  2104. head_seq = main_path[-1].sequence
  2105. snapshot = load_run_config_snapshot(trace_obj.context)
  2106. if snapshot.system_prompt_hash:
  2107. persisted_system = next(
  2108. (
  2109. message.get("content")
  2110. for message in history
  2111. if message.get("role") == "system"
  2112. and isinstance(message.get("content"), str)
  2113. ),
  2114. None,
  2115. )
  2116. if persisted_system is None or sha256(
  2117. persisted_system.encode("utf-8")
  2118. ).hexdigest() != snapshot.system_prompt_hash:
  2119. raise ValueError("persisted system prompt does not match RunConfig snapshot")
  2120. current_trace = (
  2121. await self.trace_store.get_trace(trace_id)
  2122. if self.trace_store
  2123. else None
  2124. )
  2125. if (
  2126. current_trace
  2127. and current_trace.head_sequence == 0
  2128. and policy_from_context(current_trace.context).requires_task_protocol
  2129. ):
  2130. anchor = require_root_task_anchor(current_trace.context)
  2131. anchor_text = (
  2132. "# Root Task Anchor\n\n"
  2133. + canonical_json(anchor.model_dump(mode="json"))
  2134. )
  2135. anchored_messages = []
  2136. injected = False
  2137. for message in new_messages:
  2138. if not injected and message.get("role") == "user":
  2139. content = message.get("content") or ""
  2140. if isinstance(content, str):
  2141. anchored_content = f"{anchor_text}\n\n{content}"
  2142. elif isinstance(content, list):
  2143. anchored_content = [
  2144. {"type": "text", "text": anchor_text},
  2145. *content,
  2146. ]
  2147. else:
  2148. raise ValueError(
  2149. "Recursive root anchor requires text or multimodal user content"
  2150. )
  2151. anchored_messages.append({
  2152. **message,
  2153. "content": anchored_content,
  2154. })
  2155. injected = True
  2156. else:
  2157. anchored_messages.append(message)
  2158. if not injected:
  2159. anchored_messages.append({"role": "user", "content": anchor_text})
  2160. new_messages = anchored_messages
  2161. # 2. 构建/注入 skills 到 system prompt
  2162. has_system = any(m.get("role") == "system" for m in history)
  2163. has_system_in_new = any(m.get("role") == "system" for m in new_messages)
  2164. if not has_system:
  2165. if has_system_in_new:
  2166. # 入参消息已含 system,将 skills 注入其中(在 step 4 持久化之前)
  2167. augmented = []
  2168. for msg in new_messages:
  2169. if msg.get("role") == "system":
  2170. base = msg.get("content") or ""
  2171. enriched = await self._build_system_prompt(config, base_prompt=base)
  2172. augmented.append({**msg, "content": enriched or base})
  2173. else:
  2174. augmented.append(msg)
  2175. new_messages = augmented
  2176. else:
  2177. # 没有 system,自动构建并插入历史
  2178. system_prompt = await self._build_system_prompt(config)
  2179. if system_prompt:
  2180. history = [{"role": "system", "content": system_prompt}] + history
  2181. if self.trace_store:
  2182. system_msg = Message.create(
  2183. trace_id=trace_id, role="system", sequence=sequence,
  2184. goal_id=None, content=system_prompt,
  2185. parent_sequence=None, # system message 是 root
  2186. )
  2187. await self.trace_store.add_message(system_msg)
  2188. created_messages.append(system_msg)
  2189. head_seq = sequence
  2190. sequence += 1
  2191. # 3. 追加新 messages(设置 parent_sequence 链接到当前 head)
  2192. for msg_dict in new_messages:
  2193. history.append(msg_dict)
  2194. if self.trace_store:
  2195. # 如果在侧分支中,标记为侧分支消息
  2196. if side_branch_ctx:
  2197. stored_msg = Message.create(
  2198. trace_id=trace_id,
  2199. role=msg_dict["role"],
  2200. sequence=sequence,
  2201. goal_id=goal_tree.current_id if goal_tree else None,
  2202. parent_sequence=head_seq,
  2203. branch_type=side_branch_ctx.type,
  2204. branch_id=side_branch_ctx.branch_id,
  2205. content=msg_dict.get("content"),
  2206. )
  2207. self.log.info(f"用户在侧分支 {side_branch_ctx.type} 中追加消息")
  2208. else:
  2209. stored_msg = Message.from_llm_dict(
  2210. msg_dict, trace_id=trace_id, sequence=sequence,
  2211. goal_id=None, parent_sequence=head_seq,
  2212. )
  2213. await self.trace_store.add_message(stored_msg)
  2214. created_messages.append(stored_msg)
  2215. head_seq = sequence
  2216. sequence += 1
  2217. # 5. 更新 trace 的 head_sequence
  2218. if self.trace_store and head_seq is not None:
  2219. await self.trace_store.update_trace(trace_id, head_sequence=head_seq)
  2220. persisted = await self.trace_store.get_trace(trace_id)
  2221. system_content = next(
  2222. (
  2223. message.get("content")
  2224. for message in history
  2225. if message.get("role") == "system"
  2226. and isinstance(message.get("content"), str)
  2227. ),
  2228. None,
  2229. )
  2230. if persisted and system_content is not None:
  2231. snapshot = load_run_config_snapshot(persisted.context)
  2232. # Pre-created Recursive children enter through the resume path
  2233. # on their very first execution. Bind their actual persisted
  2234. # system prompt once, just like a newly-created root Trace.
  2235. if snapshot.system_prompt_hash is None:
  2236. snapshot = snapshot.model_copy(update={
  2237. "system_prompt_hash": sha256(
  2238. system_content.encode("utf-8")
  2239. ).hexdigest()
  2240. })
  2241. persist_run_config_snapshot(persisted.context, snapshot)
  2242. await self.trace_store.update_trace(
  2243. trace_id,
  2244. context=persisted.context,
  2245. )
  2246. return history, sequence, created_messages, head_seq or 0
  2247. # ===== Phase 3: AGENT LOOP =====
  2248. async def _manage_context_usage(
  2249. self,
  2250. trace_id: str,
  2251. history: List[Dict],
  2252. goal_tree: Optional[GoalTree],
  2253. config: RunConfig,
  2254. sequence: int,
  2255. head_seq: int,
  2256. ) -> Tuple[List[Dict], int, int, bool]:
  2257. """
  2258. 管理 context 用量:检查、预警、压缩
  2259. Returns:
  2260. (updated_history, new_head_seq, next_sequence, needs_enter_compression_branch)
  2261. """
  2262. compression_config = CompressionConfig()
  2263. token_count = estimate_tokens(history)
  2264. max_tokens = compression_config.get_max_tokens(config.model)
  2265. # 计算使用率
  2266. progress_pct = (token_count / max_tokens * 100) if max_tokens > 0 else 0
  2267. msg_count = len(history)
  2268. img_count = sum(
  2269. 1 for msg in history
  2270. if isinstance(msg.get("content"), list)
  2271. for part in msg["content"]
  2272. if isinstance(part, dict) and part.get("type") in ("image", "image_url")
  2273. )
  2274. # 更新 context usage 快照
  2275. self._context_usage[trace_id] = ContextUsage(
  2276. trace_id=trace_id,
  2277. message_count=msg_count,
  2278. token_count=token_count,
  2279. max_tokens=max_tokens,
  2280. usage_percent=progress_pct,
  2281. image_count=img_count,
  2282. )
  2283. # 阈值警告(30%, 50%, 80%)
  2284. if trace_id not in self._context_warned:
  2285. self._context_warned[trace_id] = set()
  2286. for threshold in [30, 50, 80]:
  2287. if progress_pct >= threshold and threshold not in self._context_warned[trace_id]:
  2288. self._context_warned[trace_id].add(threshold)
  2289. self.log.warning(
  2290. f"Context 使用率达到 {threshold}%: {token_count:,} / {max_tokens:,} tokens ({msg_count} 条消息)"
  2291. )
  2292. # 检查是否需要压缩(仅基于 token 数量)
  2293. needs_compression = token_count > max_tokens
  2294. if not needs_compression:
  2295. return history, head_seq, sequence, False
  2296. # 检查是否有待评估知识(压缩前必须先评估)
  2297. if self.trace_store and not config.force_side_branch:
  2298. pending = await self.trace_store.get_pending_knowledge_entries(trace_id)
  2299. if pending:
  2300. # 设置侧分支队列:反思 → 知识评估 → 压缩
  2301. # 反思放在前面,确保反思期间完成的 goal 产生的新知识也能在压缩前被评估
  2302. if config.knowledge.enable_extraction:
  2303. config.force_side_branch = ["reflection", "knowledge_eval", "compression"]
  2304. else:
  2305. config.force_side_branch = ["knowledge_eval", "compression"]
  2306. # 在 trace.context 中设置触发事件
  2307. trace = await self.trace_store.get_trace(trace_id)
  2308. if trace:
  2309. if not trace.context:
  2310. trace.context = {}
  2311. trace.context["knowledge_eval_trigger"] = "compression"
  2312. await self.trace_store.update_trace(trace_id, context=trace.context)
  2313. self.log.info(f"[Knowledge Eval] 压缩前触发知识评估,待评估: {len(pending)} 条")
  2314. return history, head_seq, sequence, True
  2315. # 知识提取:在任何压缩发生前,用完整 history 做反思(进入反思侧分支)
  2316. if config.knowledge.enable_extraction and not config.force_side_branch:
  2317. # 设置侧分支队列:先反思,再压缩
  2318. config.force_side_branch = ["reflection", "compression"]
  2319. return history, head_seq, sequence, True
  2320. # 以下为未启用反思、需要压缩的情况,直接进行level 1压缩,并检查是否需要进行level 2压缩(进入侧分支)
  2321. # Level 1 压缩:Goal 完成压缩
  2322. if config.goal_compression != "none" and self.trace_store and goal_tree:
  2323. if head_seq > 0:
  2324. main_path_msgs = await self.trace_store.get_main_path_messages(
  2325. trace_id, head_seq
  2326. )
  2327. compressed_msgs = compress_completed_goals(main_path_msgs, goal_tree)
  2328. if len(compressed_msgs) < len(main_path_msgs):
  2329. self.log.info(
  2330. "Level 1 压缩: %d -> %d 条消息",
  2331. len(main_path_msgs), len(compressed_msgs),
  2332. )
  2333. history = [msg.to_llm_dict() for msg in compressed_msgs]
  2334. else:
  2335. self.log.info(
  2336. "Level 1 压缩: 无可过滤消息 (%d 条全部保留)",
  2337. len(main_path_msgs),
  2338. )
  2339. elif needs_compression:
  2340. self.log.warning(
  2341. "Token 数 (%d) 超过阈值,但无法执行 Level 1 压缩(缺少 store 或 goal_tree,或 goal_compression=none)",
  2342. token_count,
  2343. )
  2344. # Level 2 压缩:检查 Level 1 后是否仍超阈值
  2345. # 注意:Level 1 压缩后需要重新优化图片并计算 token
  2346. optimized_history_after = await self._optimize_images(
  2347. history,
  2348. config.model,
  2349. trace_id=trace_id,
  2350. )
  2351. token_count_after = estimate_tokens(optimized_history_after)
  2352. needs_level2 = token_count_after > max_tokens
  2353. if needs_level2:
  2354. self.log.info(
  2355. "Level 1 后仍超阈值 (token=%d/%d),需要进入压缩侧分支",
  2356. token_count_after, max_tokens,
  2357. )
  2358. # 如果还没有设置侧分支(说明没有启用知识提取),直接进入压缩
  2359. if not config.force_side_branch:
  2360. config.force_side_branch = ["compression"]
  2361. # 返回标志,让主循环进入侧分支
  2362. return history, head_seq, sequence, True
  2363. # 压缩完成后,输出最终发给模型的消息列表
  2364. self.log.info("Level 1 压缩完成,发送给模型的消息列表:")
  2365. for idx, msg in enumerate(history):
  2366. role = msg.get("role", "unknown")
  2367. content = msg.get("content", "")
  2368. if isinstance(content, str):
  2369. preview = content[:100] + ("..." if len(content) > 100 else "")
  2370. elif isinstance(content, list):
  2371. preview = f"[{len(content)} blocks]"
  2372. else:
  2373. preview = str(content)[:100]
  2374. self.log.info(f" [{idx}] {role}: {preview}")
  2375. return history, head_seq, sequence, False
  2376. async def _build_knowledge_eval_prompt(
  2377. self,
  2378. trace_id: str,
  2379. goal_tree: Optional[GoalTree]
  2380. ) -> str:
  2381. """构建知识评估 prompt"""
  2382. if not self.trace_store:
  2383. return ""
  2384. pending = await self.trace_store.get_pending_knowledge_entries(trace_id)
  2385. if not pending:
  2386. return ""
  2387. # 获取mission
  2388. trace = await self.trace_store.get_trace(trace_id)
  2389. mission = trace.task if trace else "未知任务"
  2390. # 获取当前Goal
  2391. current_goal = goal_tree.find(goal_tree.current_id) if goal_tree and goal_tree.current_id else None
  2392. goal_desc = current_goal.description if current_goal else "无当前目标"
  2393. # 构建知识列表
  2394. knowledge_list = []
  2395. for idx, entry in enumerate(pending, 1):
  2396. knowledge_list.append(
  2397. f"### 知识 {idx}: {entry['knowledge_id']}\n"
  2398. f"- task: {entry['task']}\n"
  2399. f"- content: {entry['content']}\n"
  2400. f"- 注入于: sequence {entry['injected_at_sequence']}, goal {entry['goal_id']}"
  2401. )
  2402. prompt = f"""你是知识评估助手。请评估以下知识在本次任务执行中的实际效果。
  2403. ## 当前任务(Mission)
  2404. {mission}
  2405. ## 当前 Goal
  2406. {goal_desc}
  2407. ## 待评估知识列表
  2408. {chr(10).join(knowledge_list)}
  2409. ## 评估维度
  2410. 1. **helpfulness**: 知识内容是否对完成任务有实质帮助?
  2411. 2. **relevance**: 执行过程中是否体现了该知识的内容?
  2412. ## 评估分类
  2413. - irrelevant: task与当前任务无关
  2414. - unused: 相关但未使用
  2415. - helpful: 有帮助
  2416. - harmful: 有负面作用
  2417. - neutral: 无明显作用
  2418. ## 输出格式
  2419. 请直接输出评估结果,使用JSON格式:
  2420. {{
  2421. "evaluations": [
  2422. {{
  2423. "knowledge_id": "knowledge-xxx",
  2424. "eval_status": "helpful",
  2425. "reason": "1-2句评估理由"
  2426. }}
  2427. ]
  2428. }}
  2429. """
  2430. return prompt
  2431. async def _single_turn_compress(
  2432. self,
  2433. trace_id: str,
  2434. history: List[Dict],
  2435. goal_tree: Optional[GoalTree],
  2436. config: RunConfig,
  2437. ) -> str:
  2438. """单次 LLM 调用生成压缩摘要,返回 summary 文本"""
  2439. self.log.info("执行单次 LLM 压缩")
  2440. # 构建压缩 prompt(使用 SINGLE_TURN_PROMPT)
  2441. from cyber_agent.core.prompts import build_single_turn_prompt
  2442. goal_prompt = goal_tree.to_prompt(include_summary=True) if goal_tree else ""
  2443. compress_prompt = build_single_turn_prompt(goal_prompt)
  2444. compress_messages = list(history) + [
  2445. {"role": "user", "content": compress_prompt}
  2446. ]
  2447. # 应用 Prompt Caching
  2448. compress_messages = self._add_cache_control(
  2449. compress_messages, config.model, config.enable_prompt_caching
  2450. )
  2451. # 单次 LLM 调用(无工具)
  2452. result = await self.call_recursive_llm(
  2453. trace_id,
  2454. purpose="ordinary",
  2455. messages=compress_messages,
  2456. model=config.model,
  2457. tools=[], # 不提供工具
  2458. temperature=config.temperature,
  2459. fail_on_post_response_exhaustion=True,
  2460. **config.extra_llm_params,
  2461. )
  2462. summary_text = result.get("content", "").strip()
  2463. # 提取 [[SUMMARY]] 块
  2464. if "[[SUMMARY]]" in summary_text:
  2465. summary_text = summary_text[
  2466. summary_text.index("[[SUMMARY]]") + len("[[SUMMARY]]"):
  2467. ].strip()
  2468. return summary_text
  2469. @staticmethod
  2470. def _try_fix_json(s: str) -> Optional[dict]:
  2471. """尝试修复常见的 JSON 截断/格式问题,返回 dict 或 None"""
  2472. import re
  2473. fixed = s.strip()
  2474. # 1. 修复值中未转义的引号(如 "key": "he said "hello" to me")
  2475. # 策略:找到 key-value 模式中值字符串内部的裸引号并转义
  2476. def _fix_inner_quotes(text: str) -> str:
  2477. # 匹配 ": "..." 模式,修复值内部的未转义引号
  2478. result = []
  2479. i = 0
  2480. while i < len(text):
  2481. # 找到 ": " 后面的值字符串开头
  2482. if text[i] == '"':
  2483. # 找到这个引号对应的字符串结束位置
  2484. j = i + 1
  2485. while j < len(text):
  2486. if text[j] == '\\':
  2487. j += 2 # 跳过转义字符
  2488. continue
  2489. if text[j] == '"':
  2490. break
  2491. j += 1
  2492. # 检查引号后面是否是合法的 JSON 分隔符
  2493. if j < len(text):
  2494. after = j + 1
  2495. # 跳过空白
  2496. while after < len(text) and text[after] in ' \t\n\r':
  2497. after += 1
  2498. if after < len(text) and text[after] not in ':,}]\n\r':
  2499. # 这个引号不是真正的结束引号,继续往后找
  2500. # 找到下一个后面跟合法分隔符的引号
  2501. k = j + 1
  2502. found_end = False
  2503. while k < len(text):
  2504. if text[k] == '"':
  2505. peek = k + 1
  2506. while peek < len(text) and text[peek] in ' \t\n\r':
  2507. peek += 1
  2508. if peek >= len(text) or text[peek] in ':,}]':
  2509. # 这才是真正的结束引号,转义中间的引号
  2510. inner = text[i+1:k].replace('"', '\\"')
  2511. result.append('"' + inner + '"')
  2512. i = k + 1
  2513. found_end = True
  2514. break
  2515. k += 1
  2516. if found_end:
  2517. continue
  2518. result.append(text[i])
  2519. i += 1
  2520. return ''.join(result)
  2521. fixed = _fix_inner_quotes(fixed)
  2522. # 2. 去掉尾部多余逗号
  2523. fixed = re.sub(r',\s*([}\]])', r'\1', fixed)
  2524. # 3. 尝试补全截断的字符串和括号
  2525. for suffix in ['', '"', '"}', '"]', '"}]', '"}}']:
  2526. try:
  2527. attempt = fixed + suffix
  2528. open_braces = attempt.count('{') - attempt.count('}')
  2529. open_brackets = attempt.count('[') - attempt.count(']')
  2530. attempt += '}' * max(0, open_braces) + ']' * max(0, open_brackets)
  2531. result = json.loads(attempt)
  2532. if isinstance(result, dict):
  2533. self.log.info(f"[JSON Fix] 成功修复 JSON (suffix={repr(suffix)})")
  2534. return result
  2535. except json.JSONDecodeError:
  2536. continue
  2537. return None
  2538. def _create_tool_approval_batch(
  2539. self,
  2540. *,
  2541. trace_id: str,
  2542. assistant_msg: Message,
  2543. tool_calls: List[Dict[str, Any]],
  2544. auto_execute_tools: bool,
  2545. ) -> ToolApprovalBatchV1:
  2546. """Compile the one persisted approval representation used by all paths."""
  2547. approval_calls: List[ToolApprovalCallV1] = []
  2548. for tool_call in tool_calls:
  2549. tool_name = tool_call.get("function", {}).get("name", "")
  2550. raw_arguments = tool_call.get("function", {}).get("arguments", {})
  2551. if isinstance(raw_arguments, str):
  2552. try:
  2553. parsed_arguments = (
  2554. json.loads(raw_arguments)
  2555. if raw_arguments.strip()
  2556. else {}
  2557. )
  2558. except json.JSONDecodeError:
  2559. parsed_arguments = {"_raw": raw_arguments}
  2560. elif isinstance(raw_arguments, dict):
  2561. parsed_arguments = dict(raw_arguments)
  2562. else:
  2563. parsed_arguments = {}
  2564. policy = self.tools.get_runtime_policy(tool_name)
  2565. requires_confirmation = (
  2566. not auto_execute_tools
  2567. or bool(policy.get("requires_confirmation"))
  2568. )
  2569. decision = "pending" if requires_confirmation else "auto_approved"
  2570. call_id = str(tool_call.get("id") or "")
  2571. approval_calls.append(ToolApprovalCallV1(
  2572. tool_call_id=call_id,
  2573. tool_name=tool_name,
  2574. original_arguments=parsed_arguments,
  2575. effective_arguments=parsed_arguments,
  2576. argument_hash=tool_argument_hash(
  2577. tool_call_id=call_id,
  2578. tool_name=tool_name,
  2579. arguments=parsed_arguments,
  2580. ),
  2581. editable_params=list(policy.get("editable_params", [])),
  2582. requires_confirmation=requires_confirmation,
  2583. decision=decision,
  2584. ))
  2585. return ToolApprovalBatchV1.create(
  2586. trace_id=trace_id,
  2587. assistant_message_id=assistant_msg.message_id,
  2588. assistant_sequence=assistant_msg.sequence,
  2589. calls=approval_calls,
  2590. )
  2591. async def _restore_orphaned_tool_approval(
  2592. self,
  2593. *,
  2594. trace: Trace,
  2595. assistant_msg: Message,
  2596. tool_calls: List[Dict[str, Any]],
  2597. config: RunConfig,
  2598. ) -> None:
  2599. """Restore the approval gate without executing an orphaned side effect."""
  2600. if not self.trace_store or not hasattr(
  2601. self.trace_store,
  2602. "get_tool_approval_batch",
  2603. ):
  2604. raise RuntimeError("TraceStore does not support tool approvals")
  2605. expected = self._create_tool_approval_batch(
  2606. trace_id=trace.trace_id,
  2607. assistant_msg=assistant_msg,
  2608. tool_calls=tool_calls,
  2609. auto_execute_tools=config.auto_execute_tools,
  2610. )
  2611. batch = await self.trace_store.get_tool_approval_batch(trace.trace_id)
  2612. if batch is None:
  2613. batch = expected
  2614. await self.trace_store.replace_tool_approval_batch(
  2615. trace.trace_id,
  2616. batch,
  2617. )
  2618. else:
  2619. same_source = (
  2620. batch.trace_id == expected.trace_id
  2621. and batch.assistant_message_id == expected.assistant_message_id
  2622. and batch.assistant_sequence == expected.assistant_sequence
  2623. and len(batch.calls) == len(expected.calls)
  2624. and all(
  2625. current.tool_call_id == wanted.tool_call_id
  2626. and current.tool_name == wanted.tool_name
  2627. and current.original_arguments == wanted.original_arguments
  2628. and current.argument_hash == wanted.argument_hash
  2629. and current.editable_params == wanted.editable_params
  2630. and current.requires_confirmation == wanted.requires_confirmation
  2631. for current, wanted in zip(batch.calls, expected.calls)
  2632. )
  2633. )
  2634. if not same_source:
  2635. raise RuntimeError(
  2636. "Persisted tool approval batch does not match the orphaned call"
  2637. )
  2638. if batch.status == "executing" or any(
  2639. call.execution_status == "executing" for call in batch.calls
  2640. ):
  2641. batch.status = "execution_unknown"
  2642. for call in batch.calls:
  2643. if call.execution_status == "executing":
  2644. call.execution_status = "execution_unknown"
  2645. batch.updated_at = datetime.now().isoformat()
  2646. await self.trace_store.replace_tool_approval_batch(
  2647. trace.trace_id,
  2648. batch,
  2649. )
  2650. raise RuntimeError(
  2651. "Tool execution outcome is unknown; refusing automatic retry"
  2652. )
  2653. if batch.status in {"execution_unknown", "completed", "cancelled"}:
  2654. raise RuntimeError(
  2655. f"Orphaned tool approval is not recoverable: {batch.status}"
  2656. )
  2657. await self.trace_store.update_trace(
  2658. trace.trace_id,
  2659. status="waiting_confirmation",
  2660. head_sequence=assistant_msg.sequence,
  2661. )
  2662. raise PendingToolApprovalRestored(
  2663. "orphaned tool call restored to persistent approval"
  2664. )
  2665. async def _resume_approved_tool_batch(
  2666. self,
  2667. *,
  2668. trace: Trace,
  2669. history: List[Dict],
  2670. goal_tree: Optional[GoalTree],
  2671. config: RunConfig,
  2672. sequence: int,
  2673. head_seq: int,
  2674. side_branch_ctx: Optional[SideBranchContext],
  2675. runtime_tool_names: set[str],
  2676. ) -> Tuple[List[Dict], int, int]:
  2677. """Execute one fully-decided persisted approval batch exactly once."""
  2678. if not config.approval_batch_id:
  2679. return history, sequence, head_seq
  2680. if not self.trace_store or not hasattr(
  2681. self.trace_store, "get_tool_approval_batch"
  2682. ):
  2683. raise RuntimeError("TraceStore does not support tool approvals")
  2684. batch = await self.trace_store.get_tool_approval_batch(trace.trace_id)
  2685. if batch is None or batch.batch_id != config.approval_batch_id:
  2686. raise RuntimeError("approved tool batch was not found")
  2687. if batch.status not in {"decided", "recoverable_candidate_command"}:
  2688. raise RuntimeError(f"tool approval batch is not executable: {batch.status}")
  2689. if batch.status == "recoverable_candidate_command":
  2690. self._validate_recoverable_candidate_approval(batch)
  2691. if any(call.decision == "pending" for call in batch.calls):
  2692. raise RuntimeError("tool approval batch still has pending decisions")
  2693. if any(call.execution_status == "executing" for call in batch.calls):
  2694. batch.status = "execution_unknown"
  2695. for call in batch.calls:
  2696. if call.execution_status == "executing":
  2697. call.execution_status = "execution_unknown"
  2698. batch.updated_at = datetime.now().isoformat()
  2699. await self.trace_store.replace_tool_approval_batch(trace.trace_id, batch)
  2700. raise RuntimeError("tool execution outcome is unknown; refusing automatic retry")
  2701. batch.status = "executing"
  2702. batch.updated_at = datetime.now().isoformat()
  2703. await self.trace_store.replace_tool_approval_batch(trace.trace_id, batch)
  2704. current_goal_id = goal_tree.current_id if goal_tree and goal_tree.current_id else None
  2705. trigger_event = None
  2706. if side_branch_ctx and side_branch_ctx.type == "knowledge_eval":
  2707. trigger_event = (trace.context.get("active_side_branch") or {}).get(
  2708. "trigger_event",
  2709. "unknown",
  2710. )
  2711. for call in batch.calls:
  2712. if call.execution_status in {"executed", "rejected"}:
  2713. continue
  2714. if call.decision == "rejected":
  2715. tool_result: Any = json.dumps({
  2716. "status": "rejected",
  2717. "error": "Tool call rejected by the local user",
  2718. }, ensure_ascii=False)
  2719. call.execution_status = "rejected"
  2720. elif call.decision in {"approved", "auto_approved"}:
  2721. call.execution_status = "executing"
  2722. batch.updated_at = datetime.now().isoformat()
  2723. await self.trace_store.replace_tool_approval_batch(
  2724. trace.trace_id,
  2725. batch,
  2726. )
  2727. try:
  2728. tool_result = await self.tools.execute(
  2729. call.tool_name,
  2730. call.effective_arguments,
  2731. uid=config.uid or "",
  2732. context=self._build_tool_context(
  2733. config=config,
  2734. trace=trace,
  2735. trace_id=trace.trace_id,
  2736. goal_id=current_goal_id,
  2737. goal_tree=goal_tree,
  2738. sequence=sequence,
  2739. head_sequence=head_seq,
  2740. tool_call_id=call.tool_call_id,
  2741. side_branch_ctx=side_branch_ctx,
  2742. trigger_event=trigger_event,
  2743. ),
  2744. allowed_tool_names=runtime_tool_names,
  2745. tool_call_id=call.tool_call_id,
  2746. approval_grant=approval_grant(batch, call),
  2747. )
  2748. except RecoverableToolExecutionError:
  2749. if len(batch.calls) != 1 or call.tool_name != "manage_candidate":
  2750. raise
  2751. # CandidateService only raises this signal after its durable,
  2752. # idempotent intent exists. Preserve the original human grant
  2753. # and call ID so a restart can publish the ledger terminal state.
  2754. call.execution_status = "not_started"
  2755. batch.status = "recoverable_candidate_command"
  2756. batch.updated_at = datetime.now().isoformat()
  2757. await self.trace_store.replace_tool_approval_batch(
  2758. trace.trace_id,
  2759. batch,
  2760. )
  2761. raise
  2762. else:
  2763. raise RuntimeError(f"unsupported tool approval decision: {call.decision}")
  2764. if isinstance(tool_result, str):
  2765. normalized = {"text": tool_result}
  2766. elif isinstance(tool_result, dict):
  2767. normalized = tool_result
  2768. else:
  2769. normalized = {"text": str(tool_result)}
  2770. tool_text = normalized.get("text", str(normalized))
  2771. tool_images = normalized.get("images", [])
  2772. artifact_refs = normalized.get("artifact_refs", [])
  2773. tool_content: Any = tool_text
  2774. if tool_images:
  2775. tool_content = [{"type": "text", "text": tool_text}]
  2776. for image in tool_images:
  2777. if image.get("type") == "base64" and image.get("data"):
  2778. media_type = image.get("media_type", "image/png")
  2779. tool_content.append({
  2780. "type": "image_url",
  2781. "image_url": {
  2782. "url": f"data:{media_type};base64,{image['data']}"
  2783. },
  2784. })
  2785. elif image.get("type") == "url" and image.get("url"):
  2786. tool_content.append({
  2787. "type": "image_url",
  2788. "image_url": {"url": image["url"]},
  2789. })
  2790. tool_msg = Message.create(
  2791. trace_id=trace.trace_id,
  2792. role="tool",
  2793. sequence=sequence,
  2794. goal_id=current_goal_id,
  2795. parent_sequence=head_seq,
  2796. tool_call_id=call.tool_call_id,
  2797. branch_type=side_branch_ctx.type if side_branch_ctx else None,
  2798. branch_id=side_branch_ctx.branch_id if side_branch_ctx else None,
  2799. content={
  2800. "tool_name": call.tool_name,
  2801. "result": tool_content,
  2802. "artifact_refs": artifact_refs,
  2803. },
  2804. )
  2805. await self.trace_store.add_message(tool_msg)
  2806. if tool_images and hasattr(self.trace_store, "write_message_attachment"):
  2807. import base64 as b64mod
  2808. for image in tool_images:
  2809. if image.get("data"):
  2810. await self.trace_store.write_message_attachment(
  2811. trace.trace_id,
  2812. tool_msg.message_id,
  2813. suffix=".png",
  2814. data=b64mod.b64decode(image["data"]),
  2815. )
  2816. break
  2817. call.result_message_id = tool_msg.message_id
  2818. if call.execution_status != "rejected":
  2819. call.execution_status = "executed"
  2820. batch.updated_at = datetime.now().isoformat()
  2821. await self.trace_store.replace_tool_approval_batch(trace.trace_id, batch)
  2822. history.append({
  2823. "role": "tool",
  2824. "tool_call_id": call.tool_call_id,
  2825. "name": call.tool_name,
  2826. "content": tool_content,
  2827. "_message_id": tool_msg.message_id,
  2828. })
  2829. head_seq = sequence
  2830. sequence += 1
  2831. batch.status = "completed"
  2832. batch.updated_at = datetime.now().isoformat()
  2833. await self.trace_store.replace_tool_approval_batch(trace.trace_id, batch)
  2834. await self.trace_store.update_trace(
  2835. trace.trace_id,
  2836. status="running",
  2837. head_sequence=head_seq,
  2838. )
  2839. config.approval_batch_id = None
  2840. return history, sequence, head_seq
  2841. @staticmethod
  2842. def _validate_recoverable_candidate_approval(batch: Any) -> None:
  2843. """Accept only the exact approved candidate command safe for replay."""
  2844. if len(batch.calls) != 1:
  2845. raise RuntimeError(
  2846. "recoverable candidate approval must contain exactly one call"
  2847. )
  2848. call = batch.calls[0]
  2849. if (
  2850. call.tool_name != "manage_candidate"
  2851. or call.decision not in {"approved", "auto_approved"}
  2852. or call.execution_status != "not_started"
  2853. ):
  2854. raise RuntimeError(
  2855. "recoverable candidate approval does not contain a replayable grant"
  2856. )
  2857. async def _mark_approval_execution_unknown(self, trace_id: str) -> bool:
  2858. """Fail closed if an approved batch stopped after execution began."""
  2859. if not self.trace_store or not hasattr(
  2860. self.trace_store, "get_tool_approval_batch"
  2861. ):
  2862. return False
  2863. batch = await self.trace_store.get_tool_approval_batch(trace_id)
  2864. if batch is None or batch.status != "executing":
  2865. return False
  2866. if await self._recover_candidate_approval_if_durable(trace_id, batch):
  2867. return False
  2868. batch.status = "execution_unknown"
  2869. batch.updated_at = datetime.now().isoformat()
  2870. for call in batch.calls:
  2871. if call.execution_status == "executing":
  2872. call.execution_status = "execution_unknown"
  2873. await self.trace_store.replace_tool_approval_batch(trace_id, batch)
  2874. await self.trace_store.update_trace(
  2875. trace_id,
  2876. status="failed",
  2877. error_message=(
  2878. "Tool execution outcome is unknown; automatic retry was refused"
  2879. ),
  2880. completed_at=datetime.now(),
  2881. )
  2882. return True
  2883. async def _recover_candidate_approval_if_durable(
  2884. self,
  2885. trace_id: str,
  2886. batch: Any,
  2887. ) -> bool:
  2888. """Recover only an exact approved candidate command with a durable intent."""
  2889. if self.candidate_service is None or len(batch.calls) != 1:
  2890. return False
  2891. call = batch.calls[0]
  2892. if (
  2893. call.tool_name != "manage_candidate"
  2894. or call.decision not in {"approved", "auto_approved"}
  2895. or call.execution_status not in {"executing", "execution_unknown"}
  2896. ):
  2897. return False
  2898. messages = await self.trace_store.get_trace_messages(trace_id)
  2899. persisted_results = [
  2900. message
  2901. for message in messages
  2902. if message.role == "tool"
  2903. and message.tool_call_id == call.tool_call_id
  2904. ]
  2905. if persisted_results:
  2906. if len(persisted_results) != 1:
  2907. return False
  2908. result_message = persisted_results[0]
  2909. content = result_message.content
  2910. if (
  2911. result_message.parent_sequence != batch.assistant_sequence
  2912. or not isinstance(content, dict)
  2913. or content.get("tool_name") != "manage_candidate"
  2914. ):
  2915. return False
  2916. call.result_message_id = result_message.message_id
  2917. call.execution_status = "executed"
  2918. batch.status = "completed"
  2919. batch.updated_at = datetime.now().isoformat()
  2920. await self.trace_store.replace_tool_approval_batch(trace_id, batch)
  2921. await self.trace_store.update_trace(
  2922. trace_id,
  2923. head_sequence=result_message.sequence,
  2924. )
  2925. return True
  2926. if not await self.candidate_service.has_replayable_version_command(
  2927. trace_id,
  2928. command_id=call.tool_call_id,
  2929. arguments=call.effective_arguments,
  2930. ):
  2931. return False
  2932. call.execution_status = "not_started"
  2933. batch.status = "recoverable_candidate_command"
  2934. batch.updated_at = datetime.now().isoformat()
  2935. await self.trace_store.replace_tool_approval_batch(trace_id, batch)
  2936. return True
  2937. async def _agent_loop(
  2938. self,
  2939. trace: Trace,
  2940. history: List[Dict],
  2941. goal_tree: Optional[GoalTree],
  2942. config: RunConfig,
  2943. sequence: int,
  2944. inject_skills: Optional[List[str]] = None,
  2945. skill_recency_threshold: int = 10,
  2946. ) -> AsyncIterator[Union[Trace, Message]]:
  2947. """执行 Agent 的 ReAct 主循环。
  2948. ``run`` 在 Trace 准备后调用;Recursive 的预算、停止、工具门禁和根验收都在此串联。
  2949. """
  2950. trace_id = trace.trace_id
  2951. runtime_tool_names = self._get_runtime_tool_names(config, trace)
  2952. tool_schemas = self._get_runtime_tool_schemas(
  2953. config,
  2954. trace,
  2955. runtime_tool_names=runtime_tool_names,
  2956. )
  2957. completion_status = "completed"
  2958. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  2959. head_seq = trace.head_sequence
  2960. # 侧分支状态(None = 主路径)
  2961. side_branch_ctx: Optional[SideBranchContext] = None
  2962. # 检查是否有未完成的侧分支需要恢复
  2963. if trace.context.get("active_side_branch"):
  2964. side_branch_data = trace.context["active_side_branch"]
  2965. branch_id = side_branch_data["branch_id"]
  2966. start_sequence = side_branch_data["start_sequence"]
  2967. # 只恢复同一持久分支;sequence 范围会把相邻分支混进来。
  2968. if self.trace_store:
  2969. all_messages = await self.trace_store.get_trace_messages(trace_id)
  2970. side_messages = [
  2971. m for m in all_messages
  2972. if (
  2973. m.sequence >= start_sequence
  2974. and m.branch_id == branch_id
  2975. and m.branch_type == side_branch_data["type"]
  2976. and m.status == "active"
  2977. )
  2978. ]
  2979. reconstructed_turns = sum(
  2980. 1 for message in side_messages if message.role == "assistant"
  2981. )
  2982. persisted_turns = int(side_branch_data.get("turns_used", 0))
  2983. turns_used = max(persisted_turns, reconstructed_turns)
  2984. if turns_used != persisted_turns or "turns_used" not in side_branch_data:
  2985. side_branch_data["turns_used"] = turns_used
  2986. await self.trace_store.update_trace(
  2987. trace_id,
  2988. context=trace.context,
  2989. )
  2990. # 恢复侧分支上下文
  2991. side_branch_ctx = SideBranchContext(
  2992. type=side_branch_data["type"],
  2993. branch_id=branch_id,
  2994. start_head_seq=side_branch_data["start_head_seq"],
  2995. start_sequence=side_branch_data["start_sequence"],
  2996. start_history_length=0, # 稍后重新计算
  2997. start_iteration=side_branch_data.get("start_iteration", 0),
  2998. max_turns=side_branch_data.get("max_turns", config.side_branch_max_turns),
  2999. turns_used=int(turns_used),
  3000. )
  3001. self.log.info(
  3002. f"恢复未完成的侧分支: {side_branch_ctx.type}, "
  3003. f"max_turns={side_branch_ctx.max_turns}"
  3004. )
  3005. # 将侧分支消息追加到 history
  3006. for m in side_messages:
  3007. history.append(m.to_llm_dict())
  3008. # 重新计算 start_history_length
  3009. side_branch_ctx.start_history_length = len(history) - len(side_messages)
  3010. # The assistant Message is the durable turn record. A crash can
  3011. # happen after that Message is stored but before Trace.context is
  3012. # updated. If reconstruction shows the budget was already
  3013. # exhausted, fail the branch closed instead of buying one extra
  3014. # model turn after restart.
  3015. if side_branch_ctx.turns_used >= side_branch_ctx.max_turns:
  3016. self.log.warning(
  3017. "恢复的侧分支 %s 已用尽轮次 %d/%d,直接返回主路径",
  3018. side_branch_ctx.type,
  3019. side_branch_ctx.turns_used,
  3020. side_branch_ctx.max_turns,
  3021. )
  3022. main_path_messages = await self.trace_store.get_main_path_messages(
  3023. trace_id,
  3024. side_branch_ctx.start_head_seq,
  3025. )
  3026. history = [message.to_llm_dict() for message in main_path_messages]
  3027. head_seq = side_branch_ctx.start_head_seq
  3028. trace.context.pop("active_side_branch", None)
  3029. if config.force_side_branch:
  3030. if config.force_side_branch[0] == side_branch_ctx.type:
  3031. config.force_side_branch.pop(0)
  3032. if not config.force_side_branch:
  3033. config.force_side_branch = None
  3034. await self.trace_store.update_trace(
  3035. trace_id,
  3036. context=trace.context,
  3037. head_sequence=head_seq,
  3038. )
  3039. side_branch_ctx = None
  3040. if config.approval_batch_id:
  3041. history, sequence, head_seq = await self._resume_approved_tool_batch(
  3042. trace=trace,
  3043. history=history,
  3044. goal_tree=goal_tree,
  3045. config=config,
  3046. sequence=sequence,
  3047. head_seq=head_seq,
  3048. side_branch_ctx=side_branch_ctx,
  3049. runtime_tool_names=runtime_tool_names,
  3050. )
  3051. break_after_side_branch = False # 侧分支退出后是否 break 主循环
  3052. for iteration in range(config.max_iterations):
  3053. # 更新活动时间(表明trace正在活跃运行)
  3054. if self.trace_store:
  3055. await self.trace_store.update_trace(
  3056. trace_id,
  3057. last_activity_at=datetime.now()
  3058. )
  3059. # 检查取消信号
  3060. cancel_event = self._cancel_events.get(trace_id)
  3061. if cancel_event and cancel_event.is_set():
  3062. self.log.info(f"Trace {trace_id} stopped by user")
  3063. trace_obj = await self._mark_trace_stopped(trace_id, head_seq)
  3064. if trace_obj:
  3065. yield trace_obj
  3066. return
  3067. # 检查Goal完成触发的知识评估
  3068. if not side_branch_ctx and self.trace_store:
  3069. trace = await self.trace_store.get_trace(trace_id)
  3070. if trace and trace.context and trace.context.get("pending_knowledge_eval"):
  3071. # 清除标志
  3072. trace.context.pop("pending_knowledge_eval", None)
  3073. await self.trace_store.update_trace(trace_id, context=trace.context)
  3074. # 设置侧分支队列
  3075. config.force_side_branch = ["knowledge_eval"]
  3076. self.log.info("[Knowledge Eval] 检测到Goal完成触发,进入知识评估侧分支")
  3077. # Context 管理(仅主路径)
  3078. needs_enter_side_branch = False
  3079. if not side_branch_ctx:
  3080. # 侧分支退出后需要 break 主循环
  3081. if break_after_side_branch and not config.force_side_branch:
  3082. break
  3083. # 检查是否强制进入侧分支(API 手动触发或自动压缩流程)
  3084. if config.force_side_branch:
  3085. needs_enter_side_branch = True
  3086. self.log.info(f"强制进入侧分支: {config.force_side_branch}")
  3087. else:
  3088. # 正常的 context 管理逻辑
  3089. history, head_seq, sequence, needs_enter_side_branch = await self._manage_context_usage(
  3090. trace_id, history, goal_tree, config, sequence, head_seq
  3091. )
  3092. # 进入侧分支
  3093. if needs_enter_side_branch and not side_branch_ctx:
  3094. # 刷新 trace,获取 _manage_context_usage 可能写入 DB 的 knowledge_eval_trigger
  3095. if self.trace_store:
  3096. fresh = await self.trace_store.get_trace(trace_id)
  3097. if fresh:
  3098. trace = fresh
  3099. # 从队列中取出第一个侧分支类型
  3100. branch_type: Literal["compression", "reflection", "knowledge_eval"]
  3101. if config.force_side_branch and isinstance(config.force_side_branch, list) and len(config.force_side_branch) > 0:
  3102. branch_type = config.force_side_branch.pop(0) # type: ignore
  3103. self.log.info(f"从队列取出侧分支: {branch_type}, 剩余队列: {config.force_side_branch}")
  3104. elif config.knowledge.enable_extraction:
  3105. # 兼容旧的单值模式(如果 force_side_branch 是字符串)
  3106. branch_type = "reflection"
  3107. else:
  3108. # 自动触发:压缩
  3109. branch_type = "compression"
  3110. branch_id = f"{branch_type}_{uuid.uuid4().hex[:8]}"
  3111. side_branch_ctx = SideBranchContext(
  3112. type=branch_type,
  3113. branch_id=branch_id,
  3114. start_head_seq=head_seq,
  3115. start_sequence=sequence,
  3116. start_history_length=len(history),
  3117. start_iteration=iteration,
  3118. max_turns=config.side_branch_max_turns,
  3119. turns_used=0,
  3120. )
  3121. # 持久化侧分支状态
  3122. if self.trace_store:
  3123. # 获取触发事件(如果是 knowledge_eval 分支)
  3124. trigger_event = trace.context.get("knowledge_eval_trigger", "unknown") if branch_type == "knowledge_eval" else None
  3125. trace.context["active_side_branch"] = {
  3126. "type": side_branch_ctx.type,
  3127. "branch_id": side_branch_ctx.branch_id,
  3128. "start_head_seq": side_branch_ctx.start_head_seq,
  3129. "start_sequence": side_branch_ctx.start_sequence,
  3130. "start_iteration": side_branch_ctx.start_iteration,
  3131. "max_turns": side_branch_ctx.max_turns,
  3132. "turns_used": side_branch_ctx.turns_used,
  3133. "started_at": datetime.now().isoformat(),
  3134. }
  3135. # 如果是 knowledge_eval 分支,添加 trigger_event
  3136. if trigger_event:
  3137. trace.context["active_side_branch"]["trigger_event"] = trigger_event
  3138. # 清除触发事件标记
  3139. trace.context.pop("knowledge_eval_trigger", None)
  3140. await self.trace_store.update_trace(
  3141. trace_id,
  3142. context=trace.context
  3143. )
  3144. # 追加侧分支 prompt
  3145. if branch_type == "reflection":
  3146. # 完成场景用全局复盘 prompt,压缩场景用阶段性反思 prompt
  3147. if break_after_side_branch:
  3148. prompt = config.knowledge.get_completion_reflect_prompt()
  3149. else:
  3150. prompt = config.knowledge.get_reflect_prompt()
  3151. elif branch_type == "knowledge_eval":
  3152. prompt = await self._build_knowledge_eval_prompt(trace_id, goal_tree)
  3153. else: # compression
  3154. from cyber_agent.trace.compaction import build_compression_prompt
  3155. prompt = build_compression_prompt(goal_tree)
  3156. branch_user_msg = Message.create(
  3157. trace_id=trace_id,
  3158. role="user",
  3159. sequence=sequence,
  3160. parent_sequence=head_seq,
  3161. goal_id=goal_tree.current_id if goal_tree else None,
  3162. branch_type=branch_type,
  3163. branch_id=branch_id,
  3164. content=prompt,
  3165. )
  3166. if self.trace_store:
  3167. await self.trace_store.add_message(branch_user_msg)
  3168. history.append(branch_user_msg.to_llm_dict())
  3169. head_seq = sequence
  3170. sequence += 1
  3171. self.log.info(f"进入侧分支: {branch_type}, branch_id={branch_id}")
  3172. continue # 跳过本轮,下一轮开始侧分支
  3173. if self.trace_store:
  3174. fresh_trace = await self.trace_store.get_trace(trace_id)
  3175. if fresh_trace:
  3176. trace = fresh_trace
  3177. runtime_policy = policy_from_context(trace.context)
  3178. runtime_tool_names = self._get_runtime_tool_names(
  3179. config,
  3180. trace,
  3181. in_side_branch=side_branch_ctx is not None,
  3182. )
  3183. tool_schemas = self._get_runtime_tool_schemas(
  3184. config,
  3185. trace,
  3186. in_side_branch=side_branch_ctx is not None,
  3187. runtime_tool_names=runtime_tool_names,
  3188. )
  3189. dispatch_allowlist = (
  3190. runtime_tool_names
  3191. if runtime_policy.mode is AgentMode.RECURSIVE
  3192. else None
  3193. )
  3194. # 构建 LLM messages(注入上下文,移除内部字段)
  3195. llm_messages = [{k: v for k, v in msg.items() if not k.startswith("_")} for msg in history]
  3196. # 优化已处理的图片(分级处理:保留/压缩/描述)
  3197. llm_messages = await self._optimize_images(
  3198. llm_messages,
  3199. config.model,
  3200. trace_id=trace_id,
  3201. )
  3202. # 对历史消息应用 Prompt Caching
  3203. llm_messages = self._add_cache_control(
  3204. llm_messages,
  3205. config.model,
  3206. config.enable_prompt_caching
  3207. )
  3208. # 调用 LLM(等待完成后再检查 cancel 信号,不中断正在进行的调用)
  3209. result = await self.call_recursive_llm(
  3210. trace_id,
  3211. purpose="ordinary",
  3212. messages=llm_messages,
  3213. model=config.model,
  3214. tools=tool_schemas,
  3215. temperature=config.temperature,
  3216. **config.extra_llm_params,
  3217. )
  3218. if (
  3219. runtime_policy.mode is AgentMode.RECURSIVE
  3220. and self.is_cancel_requested(trace_id)
  3221. ):
  3222. trace_obj = await self._mark_trace_stopped(trace_id, head_seq)
  3223. if trace_obj:
  3224. yield trace_obj
  3225. return
  3226. response_content = result.get("content", "")
  3227. reasoning_content = result.get("reasoning_content", "")
  3228. tool_calls = result.get("tool_calls")
  3229. finish_reason = result.get("finish_reason")
  3230. prompt_tokens = result.get("prompt_tokens", 0)
  3231. completion_tokens = result.get("completion_tokens", 0)
  3232. step_cost = result.get("cost", 0)
  3233. cache_creation_tokens = result.get("cache_creation_tokens")
  3234. cache_read_tokens = result.get("cache_read_tokens")
  3235. budget_exceeded_dimension = result.get("_resource_budget_exceeded")
  3236. if budget_exceeded_dimension:
  3237. tool_calls = None
  3238. finish_reason = "budget_exhausted"
  3239. lifecycle_tools = {
  3240. "agent",
  3241. "submit_task_report",
  3242. "review_task_result",
  3243. "update_task_progress",
  3244. "manage_candidate",
  3245. }
  3246. lifecycle_call_count = sum(
  3247. 1 for tc in (tool_calls or [])
  3248. if tc.get("function", {}).get("name") in lifecycle_tools
  3249. )
  3250. protocol_batch_error = None
  3251. if (
  3252. runtime_policy.requires_task_protocol
  3253. and lifecycle_call_count
  3254. and len(tool_calls or []) != 1
  3255. ):
  3256. protocol_batch_error = (
  3257. "Recursive lifecycle tools must be the only tool call in an LLM turn"
  3258. )
  3259. runtime_protocol_state = (
  3260. ensure_task_protocol(trace.context)
  3261. if runtime_policy.requires_task_protocol
  3262. else None
  3263. )
  3264. protocol_lifecycle_required = bool(
  3265. runtime_protocol_state
  3266. and (
  3267. runtime_protocol_state["pending_reviews"]
  3268. or runtime_protocol_state["next_actions"]
  3269. )
  3270. )
  3271. # 周期性自动注入上下文(仅主路径)
  3272. if (
  3273. not side_branch_ctx
  3274. and not budget_exceeded_dimension
  3275. and iteration % CONTEXT_INJECTION_INTERVAL == 0
  3276. ):
  3277. # 检查是否已经调用了 get_current_context
  3278. if tool_calls:
  3279. has_context_call = any(
  3280. tc.get("function", {}).get("name") == "get_current_context"
  3281. for tc in tool_calls
  3282. )
  3283. else:
  3284. has_context_call = False
  3285. tool_calls = []
  3286. if (
  3287. not has_context_call
  3288. and not lifecycle_call_count
  3289. and not protocol_lifecycle_required
  3290. and "get_current_context" in runtime_tool_names
  3291. ):
  3292. # 手动添加 get_current_context 工具调用
  3293. context_call_id = f"call_context_{uuid.uuid4().hex[:8]}"
  3294. tool_calls.append({
  3295. "id": context_call_id,
  3296. "type": "function",
  3297. "function": {"name": "get_current_context", "arguments": "{}"}
  3298. })
  3299. self.log.info(f"[周期性注入] 自动添加 get_current_context 工具调用 (iteration={iteration})")
  3300. # Skill 指定注入(仅主路径,首轮 iteration==0 时执行)
  3301. if (
  3302. not side_branch_ctx
  3303. and not budget_exceeded_dimension
  3304. and inject_skills
  3305. and iteration == 0
  3306. and not lifecycle_call_count
  3307. and not protocol_lifecycle_required
  3308. and "skill" in runtime_tool_names
  3309. ):
  3310. skills_to_inject = self._check_skills_need_injection(
  3311. trace, inject_skills, history, skill_recency_threshold
  3312. )
  3313. if skills_to_inject:
  3314. if not tool_calls:
  3315. tool_calls = []
  3316. for skill_name in skills_to_inject:
  3317. skill_call_id = f"call_skill_{skill_name}_{uuid.uuid4().hex[:8]}"
  3318. tool_calls.append({
  3319. "id": skill_call_id,
  3320. "type": "function",
  3321. "function": {
  3322. "name": "skill",
  3323. "arguments": json.dumps({"skill_name": skill_name})
  3324. }
  3325. })
  3326. self.log.info(f"[Skill 指定注入] 自动添加 skill(\"{skill_name}\") 工具调用")
  3327. # 按需自动创建 root goal(仅主路径)
  3328. if not side_branch_ctx and goal_tree and not goal_tree.goals and tool_calls:
  3329. has_goal_call = any(
  3330. tc.get("function", {}).get("name") == "goal"
  3331. for tc in tool_calls
  3332. )
  3333. self.log.debug(f"[Auto Root Goal] Before tool execution: goal_tree.goals={len(goal_tree.goals)}, has_goal_call={has_goal_call}, tool_calls={[tc.get('function', {}).get('name') for tc in tool_calls]}")
  3334. if not has_goal_call:
  3335. mission = goal_tree.mission
  3336. root_desc = mission[:200] if len(mission) > 200 else mission
  3337. goal_tree.add_goals(
  3338. descriptions=[root_desc],
  3339. reasons=["系统自动创建:Agent 未显式创建目标"],
  3340. parent_id=None
  3341. )
  3342. if self.trace_store:
  3343. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  3344. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  3345. self.log.info(f"自动创建 root goal: {goal_tree.goals[0].id}(未自动 focus,等待模型决定)")
  3346. else:
  3347. self.log.debug(f"[Auto Root Goal] 检测到 goal 工具调用,跳过自动创建")
  3348. # 获取当前 goal_id
  3349. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  3350. # 记录 assistant Message(parent_sequence 指向当前 head)
  3351. assistant_msg = Message.create(
  3352. trace_id=trace_id,
  3353. role="assistant",
  3354. sequence=sequence,
  3355. goal_id=current_goal_id,
  3356. parent_sequence=head_seq if head_seq > 0 else None,
  3357. branch_type=side_branch_ctx.type if side_branch_ctx else None,
  3358. branch_id=side_branch_ctx.branch_id if side_branch_ctx else None,
  3359. content={"text": response_content, "tool_calls": tool_calls, "reasoning_content": reasoning_content or None},
  3360. prompt_tokens=prompt_tokens,
  3361. completion_tokens=completion_tokens,
  3362. cache_creation_tokens=cache_creation_tokens,
  3363. cache_read_tokens=cache_read_tokens,
  3364. finish_reason=finish_reason,
  3365. cost=step_cost,
  3366. )
  3367. if self.trace_store:
  3368. await self.trace_store.add_message(assistant_msg)
  3369. # 记录模型使用
  3370. await self.trace_store.record_model_usage(
  3371. trace_id=trace_id,
  3372. sequence=sequence,
  3373. role="assistant",
  3374. model=config.model,
  3375. prompt_tokens=prompt_tokens,
  3376. completion_tokens=completion_tokens,
  3377. cache_read_tokens=cache_read_tokens or 0,
  3378. )
  3379. # 知识评估侧分支:即时检测并写入评估结果
  3380. if side_branch_ctx and side_branch_ctx.type == "knowledge_eval":
  3381. text = response_content if isinstance(response_content, str) else ""
  3382. eval_results = None
  3383. try:
  3384. eval_results = json.loads(text.strip())
  3385. if "evaluations" not in eval_results:
  3386. eval_results = None
  3387. except json.JSONDecodeError:
  3388. import re
  3389. json_match = re.search(r'```json\s*(\{.*?\})\s*```', text, re.DOTALL)
  3390. if json_match:
  3391. try:
  3392. eval_results = json.loads(json_match.group(1))
  3393. except json.JSONDecodeError:
  3394. pass
  3395. if not eval_results:
  3396. json_match = re.search(r'\{[^{]*"evaluations"[^}]*\[[^\]]*\][^}]*\}', text, re.DOTALL)
  3397. if json_match:
  3398. try:
  3399. eval_results = json.loads(json_match.group(0))
  3400. except json.JSONDecodeError:
  3401. pass
  3402. if eval_results and self.trace_store:
  3403. current_trace = await self.trace_store.get_trace(trace_id)
  3404. trigger_event = current_trace.context.get("active_side_branch", {}).get("trigger_event", "unknown")
  3405. for eval_item in eval_results.get("evaluations", []):
  3406. await self.trace_store.update_knowledge_evaluation(
  3407. trace_id=trace_id,
  3408. knowledge_id=eval_item["knowledge_id"],
  3409. eval_result={
  3410. "eval_status": eval_item["eval_status"],
  3411. "reason": eval_item.get("reason", "")
  3412. },
  3413. trigger_event=trigger_event
  3414. )
  3415. self.log.info(f"[Knowledge Eval] 已写入 {len(eval_results.get('evaluations', []))} 条评估结果")
  3416. # 一轮以成功持久化的侧分支 assistant 回复为准;先落盘计数,
  3417. # 再 yield,确保停止/重启不会重新获得已消费轮次。
  3418. if side_branch_ctx:
  3419. side_branch_ctx.turns_used += 1
  3420. active_branch = trace.context.get("active_side_branch")
  3421. if isinstance(active_branch, dict):
  3422. active_branch["turns_used"] = side_branch_ctx.turns_used
  3423. if self.trace_store:
  3424. await self.trace_store.update_trace(
  3425. trace_id,
  3426. context=trace.context,
  3427. )
  3428. yield assistant_msg
  3429. head_seq = sequence
  3430. sequence += 1
  3431. if budget_exceeded_dimension:
  3432. completion_status = "failed"
  3433. trace.context["termination_reason"] = (
  3434. f"budget_exhausted:{budget_exceeded_dimension}"
  3435. )
  3436. if self.trace_store:
  3437. await self.trace_store.update_trace(
  3438. trace_id,
  3439. context=trace.context,
  3440. error_message=trace.context["termination_reason"],
  3441. )
  3442. break
  3443. # 检查侧分支是否应该退出
  3444. if side_branch_ctx:
  3445. turns_in_branch = side_branch_ctx.turns_used
  3446. should_exit = turns_in_branch >= side_branch_ctx.max_turns or not tool_calls
  3447. if turns_in_branch >= side_branch_ctx.max_turns:
  3448. self.log.warning(
  3449. f"侧分支 {side_branch_ctx.type} 达到最大轮次 "
  3450. f"{side_branch_ctx.max_turns},强制退出"
  3451. )
  3452. if should_exit and side_branch_ctx.type == "compression":
  3453. # === 压缩侧分支退出(超时 + 正常完成统一处理)===
  3454. summary_text = ""
  3455. # 1. 从当前回复提取
  3456. if response_content:
  3457. if "[[SUMMARY]]" in response_content:
  3458. summary_text = response_content[
  3459. response_content.index("[[SUMMARY]]") + len("[[SUMMARY]]"):
  3460. ].strip()
  3461. elif response_content.strip():
  3462. summary_text = response_content.strip()
  3463. # 2. 从持久化存储按 sequence 范围查询
  3464. if not summary_text and self.trace_store:
  3465. all_messages = await self.trace_store.get_trace_messages(trace_id)
  3466. side_messages = [
  3467. m for m in all_messages
  3468. if (
  3469. m.sequence >= side_branch_ctx.start_sequence
  3470. and m.branch_id == side_branch_ctx.branch_id
  3471. and m.branch_type == side_branch_ctx.type
  3472. and m.status == "active"
  3473. )
  3474. ]
  3475. for msg in reversed(side_messages):
  3476. if msg.role == "assistant" and isinstance(msg.content, dict):
  3477. text = msg.content.get("text", "")
  3478. if "[[SUMMARY]]" in text:
  3479. summary_text = text[text.index("[[SUMMARY]]") + len("[[SUMMARY]]"):].strip()
  3480. break
  3481. elif text:
  3482. summary_text = text
  3483. break
  3484. # 3. 单次 LLM 调用
  3485. if not summary_text:
  3486. self.log.warning("侧分支未生成有效 summary,fallback 到单次 LLM 压缩")
  3487. pre_branch_history = history[:side_branch_ctx.start_history_length]
  3488. summary_text = await self._single_turn_compress(
  3489. trace_id, pre_branch_history, goal_tree, config,
  3490. )
  3491. # 创建主路径 summary 消息并重建 history
  3492. if summary_text:
  3493. # 清理侧分支指令,防止泄露到主分支
  3494. summary_text = summary_text.replace(
  3495. "**生成摘要后立即停止,不要继续执行原有任务。**", ""
  3496. ).strip()
  3497. from cyber_agent.core.prompts import build_summary_header
  3498. summary_content = build_summary_header(summary_text)
  3499. if goal_tree and goal_tree.goals:
  3500. goal_tree_detail = goal_tree.to_prompt(include_summary=True)
  3501. summary_content += f"\n\n## Current Plan\n\n{goal_tree_detail}"
  3502. # 找第一条 user message 的 sequence 作为 parent
  3503. # 续跑时 get_main_path_messages 沿 parent 链回溯,
  3504. # 指向 first_user 可以跳过所有被压缩的中间消息
  3505. first_user_seq = None
  3506. if self.trace_store:
  3507. all_msgs = await self.trace_store.get_trace_messages(trace_id)
  3508. for m in all_msgs:
  3509. if m.role == "user":
  3510. first_user_seq = m.sequence
  3511. break
  3512. summary_msg = Message.create(
  3513. trace_id=trace_id,
  3514. role="user",
  3515. sequence=sequence,
  3516. parent_sequence=first_user_seq,
  3517. branch_type=None,
  3518. content=summary_content,
  3519. )
  3520. if self.trace_store:
  3521. await self.trace_store.add_message(summary_msg)
  3522. history = self._rebuild_history_after_compression(
  3523. history, summary_msg.to_llm_dict(), label="压缩侧分支"
  3524. )
  3525. head_seq = sequence
  3526. sequence += 1
  3527. else:
  3528. self.log.error("所有压缩方案均未生成有效 summary,跳过压缩")
  3529. # 回退 history 到侧分支开始前,防止侧分支指令泄露到主分支
  3530. history = history[:side_branch_ctx.start_history_length]
  3531. head_seq = side_branch_ctx.start_head_seq
  3532. # 清理
  3533. trace.context.pop("active_side_branch", None)
  3534. config.force_side_branch = None
  3535. if self.trace_store:
  3536. await self.trace_store.update_trace(
  3537. trace_id, context=trace.context, head_sequence=head_seq,
  3538. )
  3539. side_branch_ctx = None
  3540. continue
  3541. elif should_exit and side_branch_ctx.type == "reflection":
  3542. # === 反思侧分支退出(超时 + 正常完成统一处理)===
  3543. self.log.info("反思侧分支退出")
  3544. # auto-commit hook:默认 pending 要等人工 review,
  3545. # 但 reflect_auto_commit=True 时视作全部 approved,直接批量 upload。
  3546. if (
  3547. self.trace_store
  3548. and getattr(config.knowledge, "reflect_auto_commit", False)
  3549. ):
  3550. try:
  3551. from cyber_agent.trace.extraction_review import auto_commit_branch
  3552. report = await auto_commit_branch(
  3553. self.trace_store,
  3554. trace_id,
  3555. side_branch_ctx.branch_id,
  3556. )
  3557. if report.committed or report.failed:
  3558. self.log.info(
  3559. f"[auto-commit] committed={len(report.committed)} "
  3560. f"failed={len(report.failed)} skipped={len(report.skipped)}"
  3561. )
  3562. except Exception as e:
  3563. self.log.error(f"[auto-commit] 反思分支自动提交失败: {e}")
  3564. # 恢复主路径
  3565. if self.trace_store:
  3566. main_path_messages = await self.trace_store.get_main_path_messages(
  3567. trace_id, side_branch_ctx.start_head_seq
  3568. )
  3569. history = [m.to_llm_dict() for m in main_path_messages]
  3570. head_seq = side_branch_ctx.start_head_seq
  3571. # 清理
  3572. trace.context.pop("active_side_branch", None)
  3573. if not config.force_side_branch or len(config.force_side_branch) == 0:
  3574. config.force_side_branch = None
  3575. self.log.info("反思完成,队列为空")
  3576. if self.trace_store:
  3577. await self.trace_store.update_trace(
  3578. trace_id, context=trace.context, head_sequence=head_seq,
  3579. )
  3580. side_branch_ctx = None
  3581. continue
  3582. elif should_exit and side_branch_ctx.type == "knowledge_eval":
  3583. # === 知识评估侧分支退出 ===
  3584. self.log.info("知识评估侧分支退出")
  3585. # 恢复主路径
  3586. if self.trace_store:
  3587. main_path_messages = await self.trace_store.get_main_path_messages(
  3588. trace_id, side_branch_ctx.start_head_seq
  3589. )
  3590. history = [m.to_llm_dict() for m in main_path_messages]
  3591. head_seq = side_branch_ctx.start_head_seq
  3592. # 清理
  3593. trace.context.pop("active_side_branch", None)
  3594. if not config.force_side_branch or len(config.force_side_branch) == 0:
  3595. config.force_side_branch = None
  3596. self.log.info("知识评估完成,队列为空")
  3597. if self.trace_store:
  3598. await self.trace_store.update_trace(
  3599. trace_id, context=trace.context, head_sequence=head_seq,
  3600. )
  3601. side_branch_ctx = None
  3602. continue
  3603. # 处理工具调用
  3604. # 截断兜底:finish_reason == "length" 说明响应被 max_tokens 截断,
  3605. # tool call 参数很可能不完整,不应执行,改为提示模型分批操作
  3606. if tool_calls and finish_reason == "length":
  3607. self.log.warning(
  3608. "[Runner] 响应被 max_tokens 截断,跳过 %d 个不完整的 tool calls",
  3609. len(tool_calls),
  3610. )
  3611. truncation_hint = TRUNCATION_HINT
  3612. history.append({
  3613. "role": "assistant",
  3614. "content": response_content,
  3615. "tool_calls": tool_calls,
  3616. })
  3617. # 为每个被截断的 tool call 返回错误结果
  3618. for tc in tool_calls:
  3619. history.append({
  3620. "role": "tool",
  3621. "tool_call_id": tc["id"],
  3622. "content": truncation_hint,
  3623. })
  3624. continue
  3625. if tool_calls and not config.approval_batch_id:
  3626. needs_confirmation = (
  3627. not config.auto_execute_tools
  3628. or self.tools.check_confirmation_required(tool_calls)
  3629. )
  3630. if needs_confirmation:
  3631. batch = self._create_tool_approval_batch(
  3632. trace_id=trace_id,
  3633. assistant_msg=assistant_msg,
  3634. tool_calls=tool_calls,
  3635. auto_execute_tools=config.auto_execute_tools,
  3636. )
  3637. if not self.trace_store or not hasattr(
  3638. self.trace_store, "replace_tool_approval_batch"
  3639. ):
  3640. raise RuntimeError(
  3641. "persistent TraceStore tool approval support is required"
  3642. )
  3643. await self.trace_store.replace_tool_approval_batch(
  3644. trace_id,
  3645. batch,
  3646. )
  3647. await self.trace_store.update_trace(
  3648. trace_id,
  3649. status="waiting_confirmation",
  3650. head_sequence=head_seq,
  3651. )
  3652. trace.status = "waiting_confirmation"
  3653. try:
  3654. from cyber_agent.trace.websocket import broadcast_trace_status_changed
  3655. await broadcast_trace_status_changed(
  3656. trace_id,
  3657. "waiting_confirmation",
  3658. )
  3659. except Exception:
  3660. pass
  3661. yield trace
  3662. return
  3663. if tool_calls and config.auto_execute_tools:
  3664. if (
  3665. runtime_policy.mode is AgentMode.RECURSIVE
  3666. and self.is_cancel_requested(trace_id)
  3667. ):
  3668. trace_obj = await self._mark_trace_stopped(trace_id, head_seq)
  3669. if trace_obj:
  3670. yield trace_obj
  3671. return
  3672. history.append({
  3673. "role": "assistant",
  3674. "content": response_content,
  3675. "tool_calls": tool_calls,
  3676. })
  3677. if config.parallel_tool_execution:
  3678. # === 并发执行 ===
  3679. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  3680. async def _execute_single_tool(tc: dict) -> tuple:
  3681. tool_name = tc["function"]["name"]
  3682. tool_args = tc["function"]["arguments"]
  3683. if protocol_batch_error:
  3684. return (
  3685. tc,
  3686. {},
  3687. json.dumps({
  3688. "status": "failed",
  3689. "error": protocol_batch_error,
  3690. }, ensure_ascii=False),
  3691. )
  3692. if isinstance(tool_args, str):
  3693. if not tool_args.strip():
  3694. tool_args = {}
  3695. else:
  3696. try:
  3697. tool_args = json.loads(tool_args)
  3698. except json.JSONDecodeError:
  3699. tool_args = self._try_fix_json(tool_args)
  3700. if tool_args is None:
  3701. self.log.warning(f"[Tool Call] JSON 解析失败: {tc['function']['arguments'][:200]}")
  3702. tc["function"]["arguments"] = json.dumps({"_error": "JSON parse failed", "_raw": tc["function"]["arguments"][:200]}, ensure_ascii=False)
  3703. return (tc, None, f"Error: 工具参数 JSON 格式错误,无法解析。原始参数: {tc['function']['arguments'][:200]}")
  3704. elif tool_args is None:
  3705. tool_args = {}
  3706. args_str = json.dumps(tool_args, ensure_ascii=False)
  3707. args_display = args_str[:100] + "..." if len(args_str) > 100 else args_str
  3708. self.log.info(f"[Tool Call] {tool_name}({args_display})")
  3709. trigger_event_for_tool = None
  3710. if side_branch_ctx and side_branch_ctx.type == "knowledge_eval" and self.trace_store:
  3711. current_trace = await self.trace_store.get_trace(trace_id)
  3712. if current_trace:
  3713. trigger_event_for_tool = current_trace.context.get("active_side_branch", {}).get("trigger_event", "unknown")
  3714. if tool_name in ("toolhub_call", "toolhub_search", "toolhub_health"):
  3715. try:
  3716. from cyber_agent.tools.builtin.toolhub import set_trace_context
  3717. set_trace_context(trace_id)
  3718. except ImportError:
  3719. pass
  3720. try:
  3721. tool_result = await self.tools.execute(
  3722. tool_name,
  3723. tool_args,
  3724. uid=config.uid or "",
  3725. context=self._build_tool_context(
  3726. config=config,
  3727. trace=trace,
  3728. trace_id=trace_id,
  3729. goal_id=current_goal_id,
  3730. goal_tree=goal_tree,
  3731. sequence=sequence,
  3732. head_sequence=head_seq,
  3733. tool_call_id=tc["id"],
  3734. side_branch_ctx=side_branch_ctx,
  3735. trigger_event=trigger_event_for_tool,
  3736. ),
  3737. allowed_tool_names=dispatch_allowlist,
  3738. )
  3739. return (tc, tool_args, tool_result)
  3740. except RecoverableToolExecutionError:
  3741. raise
  3742. except Exception as e:
  3743. import traceback
  3744. return (tc, tool_args, f"Error executing tool {tool_name}: {str(e)}\n{traceback.format_exc()}")
  3745. tasks = [_execute_single_tool(tc) for tc in tool_calls]
  3746. results = await asyncio.gather(*tasks)
  3747. for res in results:
  3748. tc, tool_args, tool_result = res
  3749. tool_name = tc["function"]["name"]
  3750. if tool_args is None:
  3751. history.append({"role": "tool", "tool_call_id": tc["id"], "name": tool_name, "content": tool_result})
  3752. yield Message.create(trace_id=trace_id, role="tool", sequence=sequence, parent_sequence=head_seq, tool_call_id=tc["id"], content=tool_result)
  3753. head_seq = sequence
  3754. sequence += 1
  3755. continue
  3756. if tool_name == "goal" and goal_tree:
  3757. self.log.debug(f"[Goal Tool] After execution: goal_tree.goals={len(goal_tree.goals)}, current_id={goal_tree.current_id}")
  3758. if tool_name == "upload_knowledge" and isinstance(tool_result, dict):
  3759. self.log.info(f"[Knowledge Tracking] 知识已上传")
  3760. if isinstance(tool_result, str):
  3761. tool_result = {"text": tool_result}
  3762. elif not isinstance(tool_result, dict):
  3763. tool_result = {"text": str(tool_result)}
  3764. tool_text = tool_result.get("text", str(tool_result))
  3765. tool_images = tool_result.get("images", [])
  3766. tool_usage = tool_result.get("tool_usage")
  3767. artifact_refs = tool_result.get("artifact_refs", [])
  3768. if tool_images:
  3769. tool_result_text = tool_text
  3770. tool_content_for_llm = [{"type": "text", "text": tool_text}]
  3771. for img in tool_images:
  3772. if img.get("type") == "base64" and img.get("data"):
  3773. media_type = img.get("media_type", "image/png")
  3774. tool_content_for_llm.append({"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{img['data']}"}})
  3775. elif img.get("type") == "url" and img.get("url"):
  3776. tool_content_for_llm.append({"type": "image_url", "image_url": {"url": img["url"]}})
  3777. else:
  3778. tool_result_text = tool_text
  3779. tool_content_for_llm = tool_text
  3780. tool_msg = Message.create(trace_id=trace_id, role="tool", sequence=sequence, goal_id=current_goal_id, parent_sequence=head_seq, tool_call_id=tc["id"], branch_type=side_branch_ctx.type if side_branch_ctx else None, branch_id=side_branch_ctx.branch_id if side_branch_ctx else None, content={"tool_name": tool_name, "result": tool_content_for_llm, "artifact_refs": artifact_refs})
  3781. if self.trace_store:
  3782. await self.trace_store.add_message(tool_msg)
  3783. if tool_usage:
  3784. await self.trace_store.record_model_usage(trace_id=trace_id, sequence=sequence, role="tool", tool_name=tool_name, model=tool_usage.get("model"), prompt_tokens=tool_usage.get("prompt_tokens", 0), completion_tokens=tool_usage.get("completion_tokens", 0), cache_read_tokens=tool_usage.get("cache_read_tokens", 0))
  3785. await self.record_recursive_tool_usage(
  3786. trace_id,
  3787. tool_usage,
  3788. )
  3789. if tool_images:
  3790. import base64 as b64mod
  3791. for img in tool_images:
  3792. if img.get("data"):
  3793. await self.trace_store.write_message_attachment(
  3794. trace_id,
  3795. tool_msg.message_id,
  3796. suffix=".png",
  3797. data=b64mod.b64decode(img["data"]),
  3798. )
  3799. break
  3800. yield tool_msg
  3801. head_seq = sequence
  3802. sequence += 1
  3803. history.append({"role": "tool", "tool_call_id": tc["id"], "name": tool_name, "content": tool_content_for_llm, "_message_id": tool_msg.message_id})
  3804. if tool_name == "skill" and tc["id"].startswith("call_skill_"):
  3805. try:
  3806. skill_args = json.loads(tc["function"]["arguments"]) if isinstance(tc["function"]["arguments"], str) else tc["function"]["arguments"]
  3807. injected_skill_name = skill_args.get("skill_name", "")
  3808. if injected_skill_name:
  3809. await self._update_skill_injection_record(trace_id, trace, injected_skill_name, tool_msg.message_id, tool_msg.sequence)
  3810. self.log.info(f"[Skill 指定注入] 已记录 {injected_skill_name} → msg={tool_msg.message_id}")
  3811. except Exception as e:
  3812. self.log.warning(f"[Skill 指定注入] 记录追踪失败: {e}")
  3813. else:
  3814. for tc in tool_calls:
  3815. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  3816. tool_name = tc["function"]["name"]
  3817. tool_args = tc["function"]["arguments"]
  3818. if isinstance(tool_args, str):
  3819. if not tool_args.strip():
  3820. tool_args = {}
  3821. else:
  3822. try:
  3823. tool_args = json.loads(tool_args)
  3824. except json.JSONDecodeError:
  3825. # 尝试修复常见的截断/格式问题
  3826. tool_args = self._try_fix_json(tool_args)
  3827. if tool_args is None:
  3828. self.log.warning(f"[Tool Call] JSON 解析失败,跳过工具调用 {tool_name}: {tc['function']['arguments'][:200]}")
  3829. # 修复 history 中 assistant message 里的残缺 JSON,
  3830. # 避免 Qwen API 拒绝 "function.arguments must be in JSON format"
  3831. tc["function"]["arguments"] = json.dumps(
  3832. {"_error": "JSON parse failed", "_raw": tc["function"]["arguments"][:200]},
  3833. ensure_ascii=False,
  3834. )
  3835. history.append({
  3836. "role": "tool",
  3837. "tool_call_id": tc["id"],
  3838. "content": f"Error: 工具参数 JSON 格式错误,无法解析。请重新生成正确的 JSON 参数调用此工具。原始参数: {tc['function']['arguments'][:200]}",
  3839. })
  3840. # 注意:这里不 yield Message,因为缺少必需参数会导致错误
  3841. # yield Message 应该由 trace_store 统一管理
  3842. continue
  3843. elif tool_args is None:
  3844. tool_args = {}
  3845. # 记录工具调用(INFO 级别,显示参数)
  3846. args_str = json.dumps(tool_args, ensure_ascii=False)
  3847. args_display = args_str[:100] + "..." if len(args_str) > 100 else args_str
  3848. self.log.info(f"[Tool Call] {tool_name}({args_display})")
  3849. # 获取trigger_event(如果在knowledge_eval侧分支中)
  3850. trigger_event_for_tool = None
  3851. if side_branch_ctx and side_branch_ctx.type == "knowledge_eval" and self.trace_store:
  3852. current_trace = await self.trace_store.get_trace(trace_id)
  3853. if current_trace:
  3854. trigger_event_for_tool = current_trace.context.get("active_side_branch", {}).get("trigger_event", "unknown")
  3855. # 设置 trace_id 上下文供 toolhub 使用(图片保存到 outputs/{trace_id}/)
  3856. if tool_name in ("toolhub_call", "toolhub_search", "toolhub_health"):
  3857. try:
  3858. from cyber_agent.tools.builtin.toolhub import set_trace_context
  3859. set_trace_context(trace_id)
  3860. except ImportError:
  3861. pass
  3862. if protocol_batch_error:
  3863. tool_result = json.dumps({
  3864. "status": "failed",
  3865. "error": protocol_batch_error,
  3866. }, ensure_ascii=False)
  3867. else:
  3868. tool_result = await self.tools.execute(
  3869. tool_name,
  3870. tool_args,
  3871. uid=config.uid or "",
  3872. context=self._build_tool_context(
  3873. config=config,
  3874. trace=trace,
  3875. trace_id=trace_id,
  3876. goal_id=current_goal_id,
  3877. goal_tree=goal_tree,
  3878. sequence=sequence,
  3879. head_sequence=head_seq,
  3880. tool_call_id=tc["id"],
  3881. side_branch_ctx=side_branch_ctx,
  3882. trigger_event=trigger_event_for_tool,
  3883. ),
  3884. allowed_tool_names=dispatch_allowlist,
  3885. )
  3886. # 如果是 goal 工具,记录执行后的状态
  3887. if tool_name == "goal" and goal_tree:
  3888. self.log.debug(f"[Goal Tool] After execution: goal_tree.goals={len(goal_tree.goals)}, current_id={goal_tree.current_id}")
  3889. # 跟踪上传的知识(通过 upload_knowledge)
  3890. if tool_name == "upload_knowledge" and isinstance(tool_result, dict):
  3891. metadata = tool_result.get("metadata", {})
  3892. # upload_knowledge 返回的是统计信息,不是单个 knowledge_id
  3893. # 这里只记录上传动作,不跟踪具体 ID
  3894. self.log.info(f"[Knowledge Tracking] 知识已上传到 Knowledge Manager")
  3895. # --- 支持多模态工具反馈 ---
  3896. # execute() 返回 dict{"text","images","tool_usage"} 或 str
  3897. # 统一为dict格式
  3898. if isinstance(tool_result, str):
  3899. tool_result = {"text": tool_result}
  3900. tool_text = tool_result.get("text", str(tool_result))
  3901. tool_images = tool_result.get("images", [])
  3902. tool_usage = tool_result.get("tool_usage") # 新增:提取tool_usage
  3903. artifact_refs = tool_result.get("artifact_refs", [])
  3904. # 处理多模态消息
  3905. if tool_images:
  3906. tool_result_text = tool_text
  3907. # 构建多模态消息格式
  3908. tool_content_for_llm = [{"type": "text", "text": tool_text}]
  3909. for img in tool_images:
  3910. if img.get("type") == "base64" and img.get("data"):
  3911. media_type = img.get("media_type", "image/png")
  3912. tool_content_for_llm.append({
  3913. "type": "image_url",
  3914. "image_url": {
  3915. "url": f"data:{media_type};base64,{img['data']}"
  3916. }
  3917. })
  3918. elif img.get("type") == "url" and img.get("url"):
  3919. tool_content_for_llm.append({
  3920. "type": "image_url",
  3921. "image_url": {
  3922. "url": img["url"]
  3923. }
  3924. })
  3925. img_count = len(tool_content_for_llm) - 1 # 减去 text 块
  3926. print(f"[Runner] 多模态工具反馈: tool={tool_name}, images={img_count}, text_len={len(tool_result_text)}")
  3927. else:
  3928. tool_result_text = tool_text
  3929. tool_content_for_llm = tool_text
  3930. tool_msg = Message.create(
  3931. trace_id=trace_id,
  3932. role="tool",
  3933. sequence=sequence,
  3934. goal_id=current_goal_id,
  3935. parent_sequence=head_seq,
  3936. tool_call_id=tc["id"],
  3937. branch_type=side_branch_ctx.type if side_branch_ctx else None,
  3938. branch_id=side_branch_ctx.branch_id if side_branch_ctx else None,
  3939. # 存储完整内容:有图片时保留 list(含 image_url),纯文本时存字符串
  3940. content={"tool_name": tool_name, "result": tool_content_for_llm, "artifact_refs": artifact_refs},
  3941. )
  3942. if self.trace_store:
  3943. await self.trace_store.add_message(tool_msg)
  3944. # 记录工具的模型使用
  3945. if tool_usage:
  3946. await self.trace_store.record_model_usage(
  3947. trace_id=trace_id,
  3948. sequence=sequence,
  3949. role="tool",
  3950. tool_name=tool_name,
  3951. model=tool_usage.get("model"),
  3952. prompt_tokens=tool_usage.get("prompt_tokens", 0),
  3953. completion_tokens=tool_usage.get("completion_tokens", 0),
  3954. cache_read_tokens=tool_usage.get("cache_read_tokens", 0),
  3955. )
  3956. await self.record_recursive_tool_usage(
  3957. trace_id,
  3958. tool_usage,
  3959. )
  3960. # 截图单独存为同名 PNG 文件
  3961. if tool_images:
  3962. import base64 as b64mod
  3963. for img in tool_images:
  3964. if img.get("data"):
  3965. png_path = await self.trace_store.write_message_attachment(
  3966. trace_id,
  3967. tool_msg.message_id,
  3968. suffix=".png",
  3969. data=b64mod.b64decode(img["data"]),
  3970. )
  3971. print(f"[Runner] 截图已保存: {png_path.name}")
  3972. break # 只存第一张
  3973. # 如果在侧分支,tool_msg 已持久化(不需要额外维护)
  3974. yield tool_msg
  3975. head_seq = sequence
  3976. sequence += 1
  3977. history.append({
  3978. "role": "tool",
  3979. "tool_call_id": tc["id"],
  3980. "name": tool_name,
  3981. "content": tool_content_for_llm,
  3982. "_message_id": tool_msg.message_id,
  3983. })
  3984. # 更新 skill 注入追踪记录
  3985. if tool_name == "skill" and tc["id"].startswith("call_skill_"):
  3986. try:
  3987. skill_args = json.loads(tc["function"]["arguments"]) if isinstance(tc["function"]["arguments"], str) else tc["function"]["arguments"]
  3988. injected_skill_name = skill_args.get("skill_name", "")
  3989. if injected_skill_name:
  3990. await self._update_skill_injection_record(
  3991. trace_id, trace, injected_skill_name,
  3992. tool_msg.message_id, tool_msg.sequence,
  3993. )
  3994. self.log.info(f"[Skill 指定注入] 已记录 {injected_skill_name} → msg={tool_msg.message_id}")
  3995. except Exception as e:
  3996. self.log.warning(f"[Skill 指定注入] 记录追踪失败: {e}")
  3997. # on_complete 模式:goal(done=...) 后立即压缩该 goal 的消息
  3998. if (
  3999. not side_branch_ctx
  4000. and config.goal_compression == "on_complete"
  4001. and self.trace_store
  4002. and goal_tree
  4003. ):
  4004. has_goal_done = False
  4005. for tc in tool_calls:
  4006. if tc["function"]["name"] != "goal":
  4007. continue
  4008. try:
  4009. raw = tc["function"]["arguments"]
  4010. args = json.loads(raw) if isinstance(raw, str) and raw.strip() else {}
  4011. except (json.JSONDecodeError, TypeError):
  4012. args = {}
  4013. if args.get("done") is not None:
  4014. has_goal_done = True
  4015. break
  4016. if has_goal_done:
  4017. main_path_msgs = await self.trace_store.get_main_path_messages(
  4018. trace_id, head_seq
  4019. )
  4020. compressed_msgs = compress_completed_goals(main_path_msgs, goal_tree)
  4021. if len(compressed_msgs) < len(main_path_msgs):
  4022. self.log.info(
  4023. "on_complete 压缩: %d -> %d 条消息",
  4024. len(main_path_msgs), len(compressed_msgs),
  4025. )
  4026. history = [msg.to_llm_dict() for msg in compressed_msgs]
  4027. continue # 继续循环
  4028. # 无工具调用
  4029. # 如果在侧分支中,已经在上面处理过了(不会走到这里)
  4030. # 主路径无工具调用 → 任务完成,检查是否需要完成后反思或知识评估
  4031. if not side_branch_ctx and self.trace_store:
  4032. fresh_trace = await self.trace_store.get_trace(trace_id)
  4033. if fresh_trace:
  4034. trace = fresh_trace
  4035. policy = policy_from_context(trace.context)
  4036. if policy.requires_task_protocol:
  4037. assert self.task_protocol_service is not None
  4038. def apply_completion_gate(fresh, state):
  4039. missing_report = bool(
  4040. fresh.parent_trace_id
  4041. and state.get("task_report") is None
  4042. )
  4043. pending_reviews = bool(state["pending_reviews"])
  4044. pending_actions = bool(state["next_actions"])
  4045. progress_error = (
  4046. task_progress_readiness_error(state)
  4047. if policy.requires_task_progress
  4048. and not fresh.parent_trace_id
  4049. else None
  4050. )
  4051. blocked = bool(
  4052. missing_report
  4053. or pending_reviews
  4054. or pending_actions
  4055. or progress_error
  4056. )
  4057. attempts = state["protocol_correction_attempts"]
  4058. if blocked and attempts < 2:
  4059. state["protocol_correction_attempts"] = attempts + 1
  4060. elif blocked and missing_report:
  4061. report = protocol_error_report(
  4062. trace_id,
  4063. "No valid TaskReport after two correction attempts",
  4064. )
  4065. state["task_report"] = report.model_dump()
  4066. state["task_report_submitted_at_sequence"] = sequence
  4067. state["task_report_progress_revision"] = state.get(
  4068. "task_progress_head_revision"
  4069. )
  4070. return {
  4071. "missing_report": missing_report,
  4072. "pending_reviews": pending_reviews,
  4073. "pending_actions": pending_actions,
  4074. "progress_error": progress_error,
  4075. "attempts": attempts,
  4076. "blocked": blocked,
  4077. }
  4078. gate = await self.task_protocol_service.mutate_state(
  4079. trace_id,
  4080. apply_completion_gate,
  4081. )
  4082. missing_report = gate["missing_report"]
  4083. pending_reviews = gate["pending_reviews"]
  4084. pending_actions = gate["pending_actions"]
  4085. progress_error = gate["progress_error"]
  4086. if (
  4087. gate["blocked"]
  4088. ):
  4089. attempts = gate["attempts"]
  4090. if attempts < 2:
  4091. if pending_reviews:
  4092. required_action = (
  4093. "review every pending child report with "
  4094. "review_task_result"
  4095. )
  4096. elif pending_actions:
  4097. required_action = (
  4098. "execute the approved next action with agent"
  4099. )
  4100. elif missing_report:
  4101. required_action = (
  4102. "submit a valid TaskReport with submit_task_report"
  4103. )
  4104. else:
  4105. required_action = (
  4106. "update TaskProgress to a ready_to_submit snapshot "
  4107. f"({progress_error})"
  4108. )
  4109. history.append({
  4110. "role": "user",
  4111. "content": (
  4112. "Protocol gate: you cannot finish yet. You must "
  4113. f"{required_action}."
  4114. ),
  4115. })
  4116. continue
  4117. completion_status = "failed"
  4118. await self.trace_store.update_trace(
  4119. trace_id,
  4120. error_message="Recursive task protocol gate failed",
  4121. )
  4122. break
  4123. # 检查是否有待评估的知识
  4124. if not side_branch_ctx and self.trace_store:
  4125. pending = await self.trace_store.get_pending_knowledge_entries(trace_id)
  4126. if pending:
  4127. self.log.info(f"任务即将结束,但仍有 {len(pending)} 条知识未评估,强制触发评估")
  4128. config.force_side_branch = ["knowledge_eval"]
  4129. trace = await self.trace_store.get_trace(trace_id)
  4130. if trace:
  4131. trace.context["knowledge_eval_trigger"] = "task_completion"
  4132. await self.trace_store.update_trace(trace_id, context=trace.context)
  4133. continue
  4134. if not side_branch_ctx and config.knowledge.enable_completion_extraction and not break_after_side_branch:
  4135. config.force_side_branch = ["reflection"]
  4136. break_after_side_branch = True
  4137. self.log.info("任务完成,进入完成后反思侧分支")
  4138. continue
  4139. if (
  4140. not side_branch_ctx
  4141. and self.trace_store
  4142. and policy_from_context(trace.context).requires_task_protocol
  4143. and not trace.parent_trace_id
  4144. ):
  4145. state = ensure_task_protocol(trace.context)
  4146. if (
  4147. state["root_validation_attempts"] >= 2
  4148. ):
  4149. raise ValueError(
  4150. "Root task already used its two independent validation "
  4151. "attempts; create a new trace"
  4152. )
  4153. # The Validator must read the exact persisted main path that
  4154. # produced this candidate, including real Tool Results.
  4155. await self.trace_store.update_trace(
  4156. trace_id,
  4157. head_sequence=head_seq,
  4158. )
  4159. trace.head_sequence = head_seq
  4160. validation_run = await self.validate_recursive_trace(
  4161. trace_id,
  4162. scope="root",
  4163. completion_criteria=require_root_task_anchor(
  4164. trace.context
  4165. ).completion_criteria,
  4166. candidate_output=response_content,
  4167. root_validator=True,
  4168. )
  4169. assert self.task_protocol_service is not None
  4170. def record_root_validation(fresh, state):
  4171. validation_cache = state.get("task_report_validation") or {}
  4172. validation_record = {
  4173. **validation_run.result.model_dump(),
  4174. "validation_plan": validation_cache.get("validation_plan"),
  4175. "validated_at_sequence": head_seq,
  4176. }
  4177. state["root_validation_history"].append(validation_record)
  4178. state["root_validation_attempts"] += 1
  4179. state["root_validation_passed"] = (
  4180. validation_run.result.outcome == "passed"
  4181. )
  4182. return (
  4183. state["root_validation_passed"],
  4184. state["root_validation_attempts"],
  4185. fresh,
  4186. )
  4187. root_passed, root_attempts, trace = (
  4188. await self.task_protocol_service.mutate_state(
  4189. trace_id,
  4190. record_root_validation,
  4191. )
  4192. )
  4193. if not root_passed:
  4194. if root_attempts < 2:
  4195. validation_feedback = {
  4196. "role": "user",
  4197. "content": (
  4198. "Root validation did not pass. Revise the current "
  4199. "answer using this framework-owned ValidationResult:\n"
  4200. + json.dumps(
  4201. validation_run.result.model_dump(),
  4202. ensure_ascii=False,
  4203. )
  4204. ),
  4205. }
  4206. history.append(validation_feedback)
  4207. feedback_msg = Message.from_llm_dict(
  4208. validation_feedback,
  4209. trace_id=trace_id,
  4210. sequence=sequence,
  4211. goal_id=(goal_tree.current_id if goal_tree else None),
  4212. parent_sequence=head_seq,
  4213. )
  4214. await self.trace_store.add_message(feedback_msg)
  4215. head_seq = sequence
  4216. sequence += 1
  4217. await self.trace_store.update_trace(
  4218. trace_id,
  4219. head_sequence=head_seq,
  4220. )
  4221. trace.head_sequence = head_seq
  4222. if goal_tree and goal_tree.current_id:
  4223. goal = goal_tree.find(goal_tree.current_id)
  4224. if goal:
  4225. goal.status = "in_progress"
  4226. await self.trace_store.update_goal_tree(
  4227. trace_id,
  4228. goal_tree,
  4229. )
  4230. continue
  4231. completion_status = "failed"
  4232. await self.trace_store.update_trace(
  4233. trace_id,
  4234. error_message="Root task did not pass independent validation",
  4235. )
  4236. break
  4237. if (
  4238. policy_from_context(trace.context).mode is AgentMode.RECURSIVE
  4239. and self.is_cancel_requested(trace_id)
  4240. ):
  4241. trace_obj = await self._mark_trace_stopped(trace_id, head_seq)
  4242. if trace_obj:
  4243. yield trace_obj
  4244. return
  4245. # max_iterations 等非正常退出也必须经过同一完成门禁。
  4246. if self.trace_store:
  4247. fresh_trace = await self.trace_store.get_trace(trace_id)
  4248. if fresh_trace:
  4249. trace = fresh_trace
  4250. policy = policy_from_context(trace.context)
  4251. if policy.requires_task_protocol:
  4252. assert self.task_protocol_service is not None
  4253. def close_incomplete_protocol(fresh, state):
  4254. missing_report = bool(
  4255. fresh.parent_trace_id
  4256. and state.get("task_report") is None
  4257. )
  4258. if missing_report:
  4259. report = protocol_error_report(
  4260. trace_id,
  4261. "Agent loop ended without a valid TaskReport",
  4262. )
  4263. state["task_report"] = report.model_dump()
  4264. state["task_report_submitted_at_sequence"] = sequence
  4265. state["task_report_progress_revision"] = state.get(
  4266. "task_progress_head_revision"
  4267. )
  4268. return {
  4269. "missing_report": missing_report,
  4270. "pending_reviews": bool(state["pending_reviews"]),
  4271. "pending_actions": bool(state["next_actions"]),
  4272. "root_validation_passed": bool(
  4273. state.get("root_validation_passed")
  4274. ),
  4275. "is_root": not fresh.parent_trace_id,
  4276. }
  4277. closed = await self.task_protocol_service.mutate_state(
  4278. trace_id,
  4279. close_incomplete_protocol,
  4280. )
  4281. if closed["missing_report"]:
  4282. completion_status = "failed"
  4283. await self.trace_store.update_trace(
  4284. trace_id,
  4285. error_message="Recursive task protocol gate failed",
  4286. )
  4287. if closed["pending_reviews"]:
  4288. completion_status = "failed"
  4289. if closed["pending_actions"]:
  4290. completion_status = "failed"
  4291. if (
  4292. closed["is_root"]
  4293. and not closed["root_validation_passed"]
  4294. ):
  4295. completion_status = "failed"
  4296. # 清理 trace 相关的跟踪数据
  4297. self._context_warned.pop(trace_id, None)
  4298. self._context_usage.pop(trace_id, None)
  4299. self._saved_knowledge_ids.pop(trace_id, None)
  4300. # 更新 head_sequence 并完成 Trace
  4301. if self.trace_store:
  4302. await self.trace_store.update_trace(
  4303. trace_id,
  4304. status=completion_status,
  4305. head_sequence=head_seq,
  4306. completed_at=datetime.now(),
  4307. )
  4308. if self.event_service is not None:
  4309. await self.event_service.try_pump(
  4310. trace.context.get("root_trace_id") or trace_id
  4311. )
  4312. trace_obj = await self.trace_store.get_trace(trace_id)
  4313. if trace_obj:
  4314. yield trace_obj
  4315. # ===== 压缩辅助方法 =====
  4316. def _rebuild_history_after_compression(
  4317. self,
  4318. history: List[Dict],
  4319. summary_msg_dict: Dict,
  4320. label: str = "压缩",
  4321. ) -> List[Dict]:
  4322. """
  4323. 压缩后重建 history:system prompt + 第一条 user message + summary
  4324. Args:
  4325. history: 压缩前的 history
  4326. summary_msg_dict: summary 消息的 LLM dict
  4327. label: 日志标签
  4328. Returns:
  4329. 新的 history
  4330. """
  4331. system_msg = None
  4332. first_user_msg = None
  4333. for msg in history:
  4334. if msg.get("role") == "system" and not system_msg:
  4335. system_msg = msg
  4336. elif msg.get("role") == "user" and not first_user_msg:
  4337. first_user_msg = msg
  4338. if system_msg and first_user_msg:
  4339. break
  4340. new_history = []
  4341. if system_msg:
  4342. new_history.append(system_msg)
  4343. if first_user_msg:
  4344. new_history.append(first_user_msg)
  4345. new_history.append(summary_msg_dict)
  4346. self.log.info(f"{label}完成: {len(history)} → {len(new_history)} 条消息")
  4347. for idx, msg in enumerate(new_history):
  4348. role = msg.get("role", "unknown")
  4349. content = msg.get("content", "")
  4350. if isinstance(content, str):
  4351. preview = content
  4352. elif isinstance(content, list):
  4353. preview = f"[{len(content)} blocks]"
  4354. else:
  4355. preview = str(content)
  4356. self.log.info(f" {label}后[{idx}] {role}: {preview}")
  4357. return new_history
  4358. # ===== 回溯(Rewind)=====
  4359. async def _rewind(
  4360. self,
  4361. trace_id: str,
  4362. after_sequence: int,
  4363. goal_tree: Optional[GoalTree],
  4364. ) -> int:
  4365. """
  4366. 回溯 Trace:快照 GoalTree,重建干净树并设置 ``head_sequence``。
  4367. ``_prepare_existing_trace`` 判定为回溯时调用;Recursive 同时重建待审核和待重规划状态。
  4368. Returns:
  4369. 下一个可用的 sequence 号
  4370. """
  4371. if not self.trace_store:
  4372. raise ValueError("trace_store required for rewind")
  4373. # 1. 加载所有 messages(用于 safe cutoff 和 max sequence)
  4374. all_messages = await self.trace_store.get_trace_messages(trace_id)
  4375. if not all_messages:
  4376. return 1
  4377. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  4378. cutoff = self._find_safe_cutoff(all_messages, after_sequence)
  4379. if self.candidate_service is not None:
  4380. await self.candidate_service.assert_rewind_allowed(trace_id, cutoff)
  4381. rewind_operation_id = (
  4382. f"rewind:{trace_id}:"
  4383. f"{max((item.sequence for item in all_messages), default=0)}:{cutoff}"
  4384. )
  4385. rewind_payload: dict[str, Any] = {
  4386. "operation_id": rewind_operation_id,
  4387. "after_sequence": cutoff,
  4388. "head_sequence": cutoff,
  4389. }
  4390. # 3. 快照并重建 GoalTree
  4391. if goal_tree:
  4392. # 获取截断点消息的 created_at 作为时间界限
  4393. cutoff_msg = None
  4394. for msg in all_messages:
  4395. if msg.sequence == cutoff:
  4396. cutoff_msg = msg
  4397. break
  4398. cutoff_time = cutoff_msg.created_at if cutoff_msg else datetime.now()
  4399. rewind_payload["goal_tree_snapshot"] = goal_tree.to_dict()
  4400. # 按时间重建干净的 GoalTree
  4401. new_tree = goal_tree.rebuild_for_rewind(cutoff_time)
  4402. await self.trace_store.update_goal_tree(trace_id, new_tree)
  4403. # 更新内存中的引用
  4404. goal_tree.goals = new_tree.goals
  4405. goal_tree.current_id = new_tree.current_id
  4406. trace = await self.trace_store.get_trace(trace_id)
  4407. projected_statuses: dict[str, str] = {}
  4408. if trace and policy_from_context(trace.context).requires_task_protocol:
  4409. projected_statuses = await self._rewind_protocol_state(
  4410. trace_id,
  4411. cutoff,
  4412. rewind_operation_id,
  4413. )
  4414. else:
  4415. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  4416. if goal_tree and projected_statuses:
  4417. for goal_id, status in projected_statuses.items():
  4418. goal = goal_tree.find(goal_id)
  4419. if goal:
  4420. goal.status = status
  4421. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  4422. # 4. 协议状态与 head_sequence 已在同一临界区落盘
  4423. await self.trace_store.append_event(trace_id, "rewind", rewind_payload)
  4424. if self.event_service is not None:
  4425. await self.event_service.emit_after_commit(
  4426. source_trace_id=trace_id,
  4427. event_type="run.rewound",
  4428. event_key=f"run.rewound:{rewind_operation_id}",
  4429. effective_at_sequence=cutoff,
  4430. payload={"after_sequence": cutoff},
  4431. )
  4432. # 5. 返回 next sequence(全局递增,不复用)
  4433. max_seq = max((m.sequence for m in all_messages), default=0)
  4434. return max_seq + 1
  4435. async def _rewind_protocol_state(
  4436. self,
  4437. trace_id: str,
  4438. cutoff: int,
  4439. rewind_operation_id: str,
  4440. ) -> dict[str, str]:
  4441. """Rebuild protocol state and move the Trace head in one lock domain."""
  4442. assert self.trace_store is not None
  4443. assert self.task_protocol_service is not None
  4444. async with self.task_protocol_service.locked_trace(trace_id) as trace:
  4445. state = ensure_task_protocol(trace.context)
  4446. submitted_at = state.get("task_report_submitted_at_sequence")
  4447. if isinstance(submitted_at, int) and submitted_at > cutoff:
  4448. if state.get("task_report"):
  4449. state["report_history"].append(state["task_report"])
  4450. state["task_report"] = None
  4451. state["task_report_submitted_at_sequence"] = None
  4452. state["task_report_progress_revision"] = None
  4453. state["task_report_validation"] = None
  4454. validation_cache = state.get("task_report_validation")
  4455. if (
  4456. isinstance(validation_cache, dict)
  4457. and int(validation_cache.get("validated_at_sequence", 0) or 0)
  4458. > cutoff
  4459. ):
  4460. state["task_report_validation"] = None
  4461. state["pending_reviews"] = {
  4462. child_id: entry
  4463. for child_id, entry in state["pending_reviews"].items()
  4464. if entry.get("received_at_sequence", 0) <= cutoff
  4465. }
  4466. reverted_reviews = [
  4467. review
  4468. for review in state["reviews"]
  4469. if review.get("reviewed_at_sequence", 0) > cutoff
  4470. ]
  4471. for review in reverted_reviews:
  4472. entry = review.get("pending_review")
  4473. child_id = review.get("child_trace_id")
  4474. if (
  4475. child_id
  4476. and isinstance(entry, dict)
  4477. and entry.get("received_at_sequence", 0) <= cutoff
  4478. ):
  4479. state["pending_reviews"][child_id] = entry
  4480. state["reviews"] = [
  4481. review
  4482. for review in state["reviews"]
  4483. if review.get("reviewed_at_sequence", 0) <= cutoff
  4484. ]
  4485. state["next_actions"] = [
  4486. action
  4487. for action in state["next_actions"]
  4488. if action.get("created_at_sequence", 0) <= cutoff
  4489. ]
  4490. while (
  4491. state.get("task_brief") is not None
  4492. and state.get("task_brief_effective_at_sequence", 0) > cutoff
  4493. and state.get("task_brief_history")
  4494. ):
  4495. previous = state["task_brief_history"].pop()
  4496. state["task_brief"] = previous["task_brief"]
  4497. state["task_brief_version"] = previous["version"]
  4498. state["task_brief_effective_at_sequence"] = previous.get(
  4499. "effective_at_sequence",
  4500. 0,
  4501. )
  4502. if policy_from_context(trace.context).requires_task_progress:
  4503. rewind_task_progress(state, cutoff)
  4504. state["pending_replans"] = rebuild_pending_replans(state)
  4505. root_history = [
  4506. item
  4507. for item in state.get("root_validation_history", [])
  4508. if int(
  4509. item.get(
  4510. "validated_at_sequence",
  4511. item.get("evaluated_at_sequence", 0),
  4512. )
  4513. or 0
  4514. )
  4515. <= cutoff
  4516. ]
  4517. state["root_validation_history"] = root_history
  4518. state["root_validation_attempts"] = len(root_history)
  4519. state["root_validation_passed"] = bool(
  4520. root_history and root_history[-1].get("outcome") == "passed"
  4521. )
  4522. state["protocol_correction_attempts"] = 0
  4523. prune_context_access(trace.context, cutoff)
  4524. operations = trace.context.setdefault("run_event_operations", [])
  4525. if not any(
  4526. item.get("operation_id") == rewind_operation_id
  4527. for item in operations
  4528. if isinstance(item, dict)
  4529. ):
  4530. operations.append({
  4531. "operation_id": rewind_operation_id,
  4532. "event_type": "run.rewound",
  4533. "effective_at_sequence": cutoff,
  4534. "payload": {"after_sequence": cutoff},
  4535. })
  4536. del operations[:-64]
  4537. await self.trace_store.update_trace(
  4538. trace_id,
  4539. context=trace.context,
  4540. head_sequence=cutoff,
  4541. )
  4542. projected_statuses: dict[str, str] = {}
  4543. for entry in state["pending_reviews"].values():
  4544. if entry.get("goal_id"):
  4545. projected_statuses[entry["goal_id"]] = "pending_review"
  4546. for action in state["next_actions"]:
  4547. goal_id = action.get("goal_id")
  4548. if goal_id and goal_id not in projected_statuses:
  4549. projected_statuses[goal_id] = "in_progress"
  4550. return projected_statuses
  4551. def _find_safe_cutoff(self, messages: List[Message], after_sequence: int) -> int:
  4552. """
  4553. 找到安全的截断点。
  4554. 如果 after_sequence 指向一条带 tool_calls 的 assistant message,
  4555. 则自动扩展到其所有对应的 tool response 之后。
  4556. """
  4557. cutoff = after_sequence
  4558. # 找到 after_sequence 对应的 message
  4559. target_msg = None
  4560. for msg in messages:
  4561. if msg.sequence == after_sequence:
  4562. target_msg = msg
  4563. break
  4564. if not target_msg:
  4565. return cutoff
  4566. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  4567. if target_msg.role == "assistant":
  4568. content = target_msg.content
  4569. if isinstance(content, dict) and content.get("tool_calls"):
  4570. tool_call_ids = set()
  4571. for tc in content["tool_calls"]:
  4572. if isinstance(tc, dict) and tc.get("id"):
  4573. tool_call_ids.add(tc["id"])
  4574. # 找到这些 tool_call 对应的 tool messages
  4575. for msg in messages:
  4576. if (msg.role == "tool" and msg.tool_call_id
  4577. and msg.tool_call_id in tool_call_ids):
  4578. cutoff = max(cutoff, msg.sequence)
  4579. return cutoff
  4580. async def _replay_orphaned_lifecycle_call(
  4581. self,
  4582. *,
  4583. tool_name: str,
  4584. trace: Trace,
  4585. goal_tree: Optional[GoalTree],
  4586. config: RunConfig,
  4587. assistant_msg: Message,
  4588. tool_call: Dict[str, Any],
  4589. sequence: int,
  4590. head_sequence: int,
  4591. ) -> Message:
  4592. """Replay one durable lifecycle command before another LLM turn."""
  4593. function = tool_call.get("function") or {}
  4594. raw_arguments = function.get("arguments", {})
  4595. if isinstance(raw_arguments, str):
  4596. try:
  4597. arguments = json.loads(raw_arguments) if raw_arguments.strip() else {}
  4598. except json.JSONDecodeError as exc:
  4599. raise RuntimeError(
  4600. "Orphaned lifecycle command has invalid persisted arguments"
  4601. ) from exc
  4602. elif isinstance(raw_arguments, dict):
  4603. arguments = dict(raw_arguments)
  4604. else:
  4605. raise RuntimeError(
  4606. "Orphaned lifecycle command has invalid persisted arguments"
  4607. )
  4608. tool_call_id = str(tool_call.get("id") or "")
  4609. if not tool_call_id:
  4610. raise RuntimeError("Orphaned lifecycle command has no tool_call_id")
  4611. fresh_trace = (
  4612. await self.trace_store.get_trace(trace.trace_id)
  4613. if self.trace_store
  4614. else None
  4615. )
  4616. if fresh_trace is None:
  4617. raise RuntimeError("Orphaned lifecycle Trace no longer exists")
  4618. result = await self.tools.execute(
  4619. tool_name,
  4620. arguments,
  4621. uid=config.uid or "",
  4622. context=self._build_tool_context(
  4623. config=config,
  4624. trace=fresh_trace,
  4625. trace_id=fresh_trace.trace_id,
  4626. goal_id=assistant_msg.goal_id,
  4627. goal_tree=goal_tree,
  4628. sequence=sequence,
  4629. head_sequence=head_sequence,
  4630. tool_call_id=tool_call_id,
  4631. side_branch_ctx=None,
  4632. trigger_event=None,
  4633. ),
  4634. allowed_tool_names={tool_name},
  4635. tool_call_id=tool_call_id,
  4636. )
  4637. artifact_refs: list[dict[str, Any]] = []
  4638. if isinstance(result, dict):
  4639. artifact_refs = list(result.get("artifact_refs") or [])
  4640. raw_text = result.get("text")
  4641. result_text = (
  4642. raw_text
  4643. if isinstance(raw_text, str)
  4644. else json.dumps(result, ensure_ascii=False)
  4645. )
  4646. else:
  4647. result_text = str(result)
  4648. try:
  4649. payload = json.loads(result_text)
  4650. except (json.JSONDecodeError, TypeError) as exc:
  4651. raise RuntimeError(
  4652. "Orphaned lifecycle replay returned a non-JSON result"
  4653. ) from exc
  4654. replay_completed = (
  4655. isinstance(payload, dict)
  4656. and payload.get("status") == "completed"
  4657. )
  4658. replay_failed_safely = (
  4659. tool_name == "manage_candidate"
  4660. and isinstance(payload, dict)
  4661. and payload.get("status") == "failed"
  4662. )
  4663. if not replay_completed and not replay_failed_safely:
  4664. reason = payload.get("error") if isinstance(payload, dict) else None
  4665. raise RuntimeError(
  4666. "Orphaned lifecycle replay failed closed: "
  4667. + str(reason or "unexpected tool result")
  4668. )
  4669. return Message.create(
  4670. trace_id=fresh_trace.trace_id,
  4671. role="tool",
  4672. sequence=sequence,
  4673. goal_id=assistant_msg.goal_id,
  4674. parent_sequence=head_sequence,
  4675. tool_call_id=tool_call_id,
  4676. content={
  4677. "tool_name": tool_name,
  4678. "result": result_text,
  4679. "artifact_refs": artifact_refs,
  4680. },
  4681. )
  4682. async def _heal_orphaned_tool_calls(
  4683. self,
  4684. messages: List[Message],
  4685. trace: Trace,
  4686. goal_tree: Optional[GoalTree],
  4687. config: RunConfig,
  4688. sequence: int,
  4689. ) -> tuple:
  4690. """
  4691. 检测并修复消息历史中的 orphaned tool_calls。
  4692. 当 agent 被 stop/crash 中断时,可能有 assistant 的 tool_calls 没有对应的
  4693. tool results(包括多 tool_call 部分完成的情况)。直接发给 LLM 会导致 400。
  4694. 修复策略:幂等的候选版本与父级审核命令使用原 tool_call_id
  4695. 在 LLM 前受控重放;其他缺失调用插入合成的"中断通知"消息。
  4696. - 普通工具:简短中断提示
  4697. - agent/evaluate:包含 sub_trace_id、执行统计、continue_from 指引
  4698. 合成消息持久化到 store,确保幂等(下次续跑不再触发)。
  4699. Returns:
  4700. (healed_messages, next_sequence)
  4701. """
  4702. if not messages:
  4703. return messages, sequence
  4704. # 收集所有 tool_call IDs → (assistant_msg, tool_call_dict)
  4705. tc_map: Dict[str, tuple] = {}
  4706. result_ids: set = set()
  4707. for msg in messages:
  4708. if msg.role == "assistant":
  4709. content = msg.content
  4710. if isinstance(content, dict) and content.get("tool_calls"):
  4711. for tc in content["tool_calls"]:
  4712. tc_id = tc.get("id")
  4713. if tc_id:
  4714. tc_map[tc_id] = (msg, tc)
  4715. elif msg.role == "tool" and msg.tool_call_id:
  4716. result_ids.add(msg.tool_call_id)
  4717. orphaned_ids = [tc_id for tc_id in tc_map if tc_id not in result_ids]
  4718. if not orphaned_ids:
  4719. return messages, sequence
  4720. self.log.info(
  4721. "检测到 %d 个 orphaned tool_calls,生成合成中断通知",
  4722. len(orphaned_ids),
  4723. )
  4724. healed = list(messages)
  4725. head_seq = messages[-1].sequence
  4726. for tc_id in orphaned_ids:
  4727. assistant_msg, tc = tc_map[tc_id]
  4728. tool_name = tc.get("function", {}).get("name", "unknown")
  4729. if tool_name in {"manage_candidate", "review_task_result"}:
  4730. assistant_calls = (
  4731. assistant_msg.content.get("tool_calls", [])
  4732. if isinstance(assistant_msg.content, dict)
  4733. else []
  4734. )
  4735. if len(assistant_calls) != 1:
  4736. raise RuntimeError(
  4737. "Orphaned lifecycle-exclusive command was persisted in a mixed batch"
  4738. )
  4739. needs_confirmation = (
  4740. not config.auto_execute_tools
  4741. or self.tools.check_confirmation_required([tc])
  4742. )
  4743. persisted_approval = (
  4744. await self.trace_store.get_tool_approval_batch(trace.trace_id)
  4745. if self.trace_store
  4746. and hasattr(self.trace_store, "get_tool_approval_batch")
  4747. else None
  4748. )
  4749. if needs_confirmation or persisted_approval is not None:
  4750. await self._restore_orphaned_tool_approval(
  4751. trace=trace,
  4752. assistant_msg=assistant_msg,
  4753. tool_calls=[tc],
  4754. config=config,
  4755. )
  4756. replayed = await self._replay_orphaned_lifecycle_call(
  4757. tool_name=tool_name,
  4758. trace=trace,
  4759. goal_tree=goal_tree,
  4760. config=config,
  4761. assistant_msg=assistant_msg,
  4762. tool_call=tc,
  4763. sequence=sequence,
  4764. head_sequence=head_seq,
  4765. )
  4766. if self.trace_store:
  4767. await self.trace_store.add_message(replayed)
  4768. healed.append(replayed)
  4769. head_seq = sequence
  4770. sequence += 1
  4771. continue
  4772. if tool_name in ("agent", "evaluate"):
  4773. result_text = self._build_agent_interrupted_result(
  4774. tc, goal_tree, assistant_msg,
  4775. )
  4776. else:
  4777. result_text = build_tool_interrupted_message(tool_name)
  4778. synthetic_msg = Message.create(
  4779. trace_id=trace.trace_id,
  4780. role="tool",
  4781. sequence=sequence,
  4782. goal_id=assistant_msg.goal_id,
  4783. parent_sequence=head_seq,
  4784. tool_call_id=tc_id,
  4785. content={"tool_name": tool_name, "result": result_text},
  4786. )
  4787. if self.trace_store:
  4788. await self.trace_store.add_message(synthetic_msg)
  4789. healed.append(synthetic_msg)
  4790. head_seq = sequence
  4791. sequence += 1
  4792. # 更新 trace head/last sequence
  4793. if self.trace_store:
  4794. await self.trace_store.update_trace(
  4795. trace.trace_id,
  4796. head_sequence=head_seq,
  4797. last_sequence=max(head_seq, sequence - 1),
  4798. )
  4799. return healed, sequence
  4800. def _build_agent_interrupted_result(
  4801. self,
  4802. tc: Dict,
  4803. goal_tree: Optional[GoalTree],
  4804. assistant_msg: Message,
  4805. ) -> str:
  4806. """为中断的 agent/evaluate 工具调用构建合成结果(对齐正常返回值格式)"""
  4807. args_str = tc.get("function", {}).get("arguments", "{}")
  4808. try:
  4809. args = json.loads(args_str) if isinstance(args_str, str) else args_str
  4810. except json.JSONDecodeError:
  4811. args = {}
  4812. task = args.get("task", "未知任务")
  4813. if isinstance(task, list):
  4814. task = "; ".join(task)
  4815. tool_name = tc.get("function", {}).get("name", "agent")
  4816. mode = "evaluate" if tool_name == "evaluate" else "delegate"
  4817. # 从 goal_tree 查找 sub_trace 信息
  4818. sub_trace_id = None
  4819. stats = None
  4820. if goal_tree and assistant_msg.goal_id:
  4821. goal = goal_tree.find(assistant_msg.goal_id)
  4822. if goal and goal.sub_trace_ids:
  4823. first = goal.sub_trace_ids[0]
  4824. if isinstance(first, dict):
  4825. sub_trace_id = first.get("trace_id")
  4826. elif isinstance(first, str):
  4827. sub_trace_id = first
  4828. if goal.cumulative_stats:
  4829. s = goal.cumulative_stats
  4830. if s.message_count > 0:
  4831. stats = {
  4832. "message_count": s.message_count,
  4833. "total_tokens": s.total_tokens,
  4834. "total_cost": round(s.total_cost, 4),
  4835. }
  4836. result: Dict[str, Any] = {
  4837. "mode": mode,
  4838. "status": "interrupted",
  4839. "summary": AGENT_INTERRUPTED_SUMMARY,
  4840. "task": task,
  4841. }
  4842. if sub_trace_id:
  4843. result["sub_trace_id"] = sub_trace_id
  4844. result["hint"] = build_agent_continue_hint(sub_trace_id)
  4845. if stats:
  4846. result["stats"] = stats
  4847. return json.dumps(result, ensure_ascii=False, indent=2)
  4848. # ===== 上下文注入 =====
  4849. # ===== Skill 指定注入 =====
  4850. def _check_skills_need_injection(
  4851. self,
  4852. trace: Trace,
  4853. inject_skills: List[str],
  4854. history: List[Dict],
  4855. recency_threshold: int,
  4856. ) -> List[str]:
  4857. """
  4858. 检查哪些 skill 需要注入。
  4859. 通过 trace.context["injected_skills"] 中记录的 message_id
  4860. 检查是否仍在当前 history 的最近 recency_threshold 条消息中。
  4861. Returns:
  4862. 需要注入的 skill 名称列表
  4863. """
  4864. injected = (trace.context or {}).get("injected_skills", {})
  4865. # 收集 history 中最近 recency_threshold 条消息的 message_id
  4866. recent_msgs = history[-recency_threshold:] if recency_threshold > 0 else []
  4867. recent_ids = set()
  4868. for msg in recent_msgs:
  4869. mid = msg.get("message_id") or msg.get("_message_id")
  4870. if mid:
  4871. recent_ids.add(mid)
  4872. needs_inject = []
  4873. for skill_name in inject_skills:
  4874. record = injected.get(skill_name)
  4875. if not record:
  4876. needs_inject.append(skill_name)
  4877. continue
  4878. if record.get("message_id") not in recent_ids:
  4879. needs_inject.append(skill_name)
  4880. return needs_inject
  4881. async def _update_skill_injection_record(
  4882. self,
  4883. trace_id: str,
  4884. trace: Trace,
  4885. skill_name: str,
  4886. message_id: str,
  4887. sequence: int,
  4888. ):
  4889. """更新 trace.context 中的 skill 注入记录"""
  4890. if not trace.context:
  4891. trace.context = {}
  4892. if "injected_skills" not in trace.context:
  4893. trace.context["injected_skills"] = {}
  4894. trace.context["injected_skills"][skill_name] = {
  4895. "message_id": message_id,
  4896. "sequence": sequence,
  4897. }
  4898. if self.trace_store:
  4899. await self.trace_store.update_trace(trace_id, context=trace.context)
  4900. # ===== 上下文注入 =====
  4901. def _build_context_injection(
  4902. self,
  4903. trace: Trace,
  4904. goal_tree: Optional[GoalTree],
  4905. ) -> str:
  4906. """构建周期性注入的上下文(GoalTree + Active Collaborators + Focus 提醒 + IM 消息通知)"""
  4907. from datetime import datetime
  4908. parts = [f"## Current Time\n\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"]
  4909. if trace and policy_from_context(trace.context).requires_task_protocol:
  4910. parts.append(render_recursive_context(trace.context))
  4911. # GoalTree
  4912. if goal_tree and goal_tree.goals:
  4913. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  4914. if goal_tree.current_id:
  4915. # 检测 focus 在有子节点的父目标上:提醒模型 focus 到具体子目标
  4916. children = goal_tree.get_children(goal_tree.current_id)
  4917. pending_children = [c for c in children if c.status in ("pending", "in_progress")]
  4918. if pending_children:
  4919. child_ids = ", ".join(
  4920. goal_tree._generate_display_id(c) for c in pending_children[:3]
  4921. )
  4922. parts.append(
  4923. f"**提醒**:当前焦点在父目标上,建议用 `goal(focus=\"...\")` "
  4924. f"切换到具体子目标(如 {child_ids})再执行。"
  4925. )
  4926. else:
  4927. # 无焦点:提醒模型 focus
  4928. parts.append(
  4929. "**提醒**:当前没有焦点目标。请用 `goal(focus=\"...\")` 选择一个目标开始执行。"
  4930. )
  4931. # Active Collaborators
  4932. collaborators = trace.context.get("collaborators", [])
  4933. if collaborators:
  4934. lines = ["## Active Collaborators"]
  4935. for c in collaborators:
  4936. status_str = c.get("status", "unknown")
  4937. ctype = c.get("type", "agent")
  4938. summary = c.get("summary", "")
  4939. name = c.get("name", "unnamed")
  4940. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  4941. parts.append("\n".join(lines))
  4942. # IM 消息通知(Research Agent)
  4943. im_config = trace.context.get("im_config")
  4944. if im_config:
  4945. contact_id = im_config.get("contact_id")
  4946. chat_id = im_config.get("chat_id")
  4947. if contact_id and chat_id:
  4948. # 尝试导入 IM 模块并检查通知
  4949. try:
  4950. from cyber_agent.tools.builtin.im import chat as im_chat
  4951. notification = im_chat._notifications.get((contact_id, chat_id))
  4952. if notification:
  4953. count = notification.get("count", 0)
  4954. senders = notification.get("from", [])
  4955. senders_str = ", ".join(senders)
  4956. parts.append(
  4957. f"## IM 消息通知\n\n"
  4958. f"你有 {count} 条新消息,来自: {senders_str}\n"
  4959. f"使用 `im_receive_messages(contact_id=\"{contact_id}\", chat_id=\"{chat_id}\")` 查看消息内容。"
  4960. )
  4961. else:
  4962. parts.append("## IM 消息通知\n\n暂无新消息")
  4963. except (ImportError, AttributeError):
  4964. # IM 模块未加载或不可用
  4965. pass
  4966. # Knowledge Manager 队列状态
  4967. km_queue_size = trace.context.get("km_queue_size")
  4968. if km_queue_size is not None:
  4969. current_sender = trace.context.get("current_sender", "unknown")
  4970. if km_queue_size > 0:
  4971. parts.append(
  4972. f"## 消息队列状态\n\n"
  4973. f"当前处理: {current_sender} 的消息\n"
  4974. f"队列中还有 {km_queue_size} 条待处理消息"
  4975. )
  4976. else:
  4977. parts.append(
  4978. f"## 消息队列状态\n\n"
  4979. f"当前处理: {current_sender} 的消息\n"
  4980. f"队列为空,处理完本条消息后将进入休眠"
  4981. )
  4982. return "\n\n".join(parts)
  4983. # ===== 辅助方法 =====
  4984. async def _optimize_images(
  4985. self,
  4986. messages: List[Dict],
  4987. model: str,
  4988. *,
  4989. trace_id: Optional[str] = None,
  4990. ) -> List[Dict]:
  4991. """
  4992. 分级优化已处理的图片,节省 token
  4993. 策略(基于图片距离最后一条 assistant 的"轮次"):
  4994. 1. 最近 1-2 轮:保留原图
  4995. 2. 3-5 轮:降低分辨率和压缩(节省 token 但保留视觉信息)
  4996. 3. 5 轮以上:调用小模型生成文本描述 + 保留 URL
  4997. 处理结果会缓存,避免重复的 PIL 解码/编码和 LLM 调用。
  4998. Args:
  4999. messages: 原始消息列表
  5000. model: 当前使用的模型(用于选择描述生成模型)
  5001. Returns:
  5002. 优化后的消息列表(深拷贝)
  5003. """
  5004. if not messages:
  5005. return messages
  5006. # 找到最后一条 assistant message 的位置
  5007. last_assistant_idx = -1
  5008. for i in range(len(messages) - 1, -1, -1):
  5009. if messages[i].get("role") == "assistant":
  5010. last_assistant_idx = i
  5011. break
  5012. # 如果没有 assistant message,说明还没开始对话,不优化
  5013. if last_assistant_idx == -1:
  5014. return messages
  5015. # 统计从每个位置到最后一条 assistant 之间的 assistant 数量(作为"轮次")
  5016. assistant_count_after = [0] * len(messages)
  5017. count = 0
  5018. for i in range(len(messages) - 1, -1, -1):
  5019. assistant_count_after[i] = count
  5020. if messages[i].get("role") == "assistant":
  5021. count += 1
  5022. # 深拷贝避免修改原始数据
  5023. import copy
  5024. import hashlib
  5025. import asyncio
  5026. import base64 as b64mod
  5027. import httpx
  5028. import mimetypes
  5029. messages = copy.deepcopy(messages)
  5030. # 预处理:将所有 HTTP(S) URL 图片下载并转为 base64 data URL
  5031. # Qwen API 无法访问外部签名 URL(如 BFL、火山引擎 TOS),必须在本地转换
  5032. url_download_jobs = [] # [(msg_idx, block_idx, url)]
  5033. for i, msg in enumerate(messages):
  5034. if msg.get("role") != "tool":
  5035. continue
  5036. content = msg.get("content")
  5037. if not isinstance(content, list):
  5038. continue
  5039. for block_idx, block in enumerate(content):
  5040. if isinstance(block, dict) and block.get("type") == "image_url":
  5041. url = block.get("image_url", {}).get("url", "")
  5042. if url.startswith(("http://", "https://")):
  5043. url_download_jobs.append((i, block_idx, url))
  5044. if url_download_jobs:
  5045. async def _download_image_to_data_url(url: str) -> str | None:
  5046. try:
  5047. async with httpx.AsyncClient(timeout=60, trust_env=False) as client:
  5048. resp = await client.get(url)
  5049. resp.raise_for_status()
  5050. ct = resp.headers.get("content-type", "").split(";")[0].strip()
  5051. if not ct.startswith("image/"):
  5052. ct = mimetypes.guess_type(url.split("?")[0])[0] or "image/png"
  5053. b64 = b64mod.b64encode(resp.content).decode()
  5054. return f"data:{ct};base64,{b64}"
  5055. except Exception:
  5056. return None
  5057. results = await asyncio.gather(
  5058. *[_download_image_to_data_url(url) for _, _, url in url_download_jobs],
  5059. return_exceptions=True
  5060. )
  5061. converted = 0
  5062. for (msg_idx, block_idx, original_url), result in zip(url_download_jobs, results):
  5063. if isinstance(result, str) and result.startswith("data:"):
  5064. messages[msg_idx]["content"][block_idx]["image_url"]["url"] = result
  5065. converted += 1
  5066. if converted:
  5067. self.log.info(f"[Image Optimization] URL→base64 预转换: {converted}/{len(url_download_jobs)} 张")
  5068. # 统计优化情况
  5069. stats = {"kept": 0, "downscaled": 0, "described": 0, "cache_hit": 0}
  5070. # 收集需要降分辨率或尺寸补齐的图片(用于并发处理)
  5071. process_jobs = [] # [(msg_idx, block_idx, image_url, cache_key, max_size, cache_field)]
  5072. # 第一遍:扫描并收集需要处理的图片
  5073. for i in range(last_assistant_idx):
  5074. msg = messages[i]
  5075. if msg.get("role") != "tool":
  5076. continue
  5077. content = msg.get("content")
  5078. if not isinstance(content, list):
  5079. continue
  5080. rounds_ago = assistant_count_after[i]
  5081. for block_idx, block in enumerate(content):
  5082. if isinstance(block, dict) and block.get("type") == "image_url":
  5083. image_url_obj = block.get("image_url", {})
  5084. image_url = image_url_obj.get("url", "")
  5085. if image_url.startswith("data:"):
  5086. cache_key = hashlib.md5(image_url[:200].encode()).hexdigest()
  5087. else:
  5088. cache_key = hashlib.md5(image_url.encode()).hexdigest()
  5089. # 1-5 轮都需要检查尺寸
  5090. if rounds_ago <= 5:
  5091. cached = self._image_opt_cache.get(cache_key, {})
  5092. cache_field = "pad_only" if rounds_ago <= 2 else "downscaled"
  5093. if cache_field not in cached and image_url.startswith("data:"):
  5094. max_size = None if rounds_ago <= 2 else 512
  5095. process_jobs.append((i, block_idx, image_url, cache_key, max_size, cache_field))
  5096. # 并发处理所有尺寸任务
  5097. if process_jobs:
  5098. process_results = await asyncio.gather(
  5099. *[self._process_image_size(url, max_size=ms) for _, _, url, _, ms, _ in process_jobs],
  5100. return_exceptions=True
  5101. )
  5102. for (_, _, _, cache_key, _, cache_field), result in zip(process_jobs, process_results):
  5103. if not isinstance(result, Exception) and result is not None:
  5104. self._image_opt_cache.setdefault(cache_key, {})[cache_field] = result
  5105. # 第二遍:应用处理结果
  5106. for i in range(last_assistant_idx):
  5107. msg = messages[i]
  5108. if msg.get("role") != "tool":
  5109. continue
  5110. content = msg.get("content")
  5111. if not isinstance(content, list):
  5112. continue
  5113. # 计算这条消息距离最后一条 assistant 的"轮次"
  5114. rounds_ago = assistant_count_after[i]
  5115. # 处理每个 content block
  5116. new_content = []
  5117. for block in content:
  5118. if isinstance(block, dict) and block.get("type") == "image_url":
  5119. image_url_obj = block.get("image_url", {})
  5120. image_url = image_url_obj.get("url", "")
  5121. # 生成缓存 key(URL 图片用 URL 本身,base64 用前 64 字符 hash)
  5122. if image_url.startswith("data:"):
  5123. cache_key = hashlib.md5(image_url[:200].encode()).hexdigest()
  5124. else:
  5125. cache_key = hashlib.md5(image_url.encode()).hexdigest()
  5126. # 根据距离决定处理策略
  5127. if rounds_ago <= 2:
  5128. # 最近 1-2 轮:只补齐过小图片,保留原分辨率
  5129. cached = self._image_opt_cache.get(cache_key, {})
  5130. if "pad_only" in cached:
  5131. new_content.append({
  5132. "type": "image_url",
  5133. "image_url": {"url": cached["pad_only"]}
  5134. })
  5135. stats["kept"] += 1
  5136. stats["cache_hit"] += 1
  5137. elif image_url.startswith("data:"):
  5138. processed = await self._process_image_size(image_url, max_size=None)
  5139. if processed:
  5140. self._image_opt_cache.setdefault(cache_key, {})["pad_only"] = processed
  5141. new_content.append({
  5142. "type": "image_url",
  5143. "image_url": {"url": processed}
  5144. })
  5145. else:
  5146. new_content.append(block)
  5147. stats["kept"] += 1
  5148. else:
  5149. new_content.append(block)
  5150. stats["kept"] += 1
  5151. elif rounds_ago <= 5:
  5152. # 3-5 轮:降低分辨率(优先从缓存取)
  5153. cached = self._image_opt_cache.get(cache_key, {})
  5154. if "downscaled" in cached:
  5155. new_content.append({
  5156. "type": "image_url",
  5157. "image_url": {"url": cached["downscaled"]}
  5158. })
  5159. stats["downscaled"] += 1
  5160. stats["cache_hit"] += 1
  5161. elif image_url.startswith("data:"):
  5162. processed = await self._process_image_size(image_url, max_size=512)
  5163. if processed:
  5164. # 缓存结果
  5165. self._image_opt_cache.setdefault(cache_key, {})["downscaled"] = processed
  5166. new_content.append({
  5167. "type": "image_url",
  5168. "image_url": {"url": processed}
  5169. })
  5170. stats["downscaled"] += 1
  5171. else:
  5172. new_content.append(block)
  5173. stats["kept"] += 1
  5174. else:
  5175. # URL 图片:无法直接处理,保留原图
  5176. new_content.append(block)
  5177. stats["kept"] += 1
  5178. else:
  5179. # 5 轮以上:生成文本描述(优先从缓存取)
  5180. cached = self._image_opt_cache.get(cache_key, {})
  5181. if "description" in cached:
  5182. new_content.append(cached["description"])
  5183. stats["described"] += 1
  5184. stats["cache_hit"] += 1
  5185. else:
  5186. description = await self._generate_image_description(
  5187. image_url,
  5188. model,
  5189. trace_id=trace_id,
  5190. )
  5191. url_info = f" (URL: {image_url[:100]}...)" if not image_url.startswith("data:") else ""
  5192. desc_block = {
  5193. "type": "text",
  5194. "text": f"[Image description: {description}]{url_info}"
  5195. }
  5196. # 缓存结果
  5197. self._image_opt_cache.setdefault(cache_key, {})["description"] = desc_block
  5198. new_content.append(desc_block)
  5199. stats["described"] += 1
  5200. else:
  5201. new_content.append(block)
  5202. msg["content"] = new_content
  5203. # print(f"[Image Opt Check] 扫描到 {stats['kept'] + stats['downscaled'] + stats['described']} 张图片上下文")
  5204. if stats["downscaled"] > 0 or stats["described"] > 0:
  5205. self.log.info(
  5206. f"[Image Optimization] 保留 {stats['kept']} 张,"
  5207. f"降分辨率 {stats['downscaled']} 张,"
  5208. f"文本描述 {stats['described']} 张,"
  5209. f"缓存命中 {stats['cache_hit']} 次"
  5210. )
  5211. return messages
  5212. async def _process_image_size(self, base64_url: str, max_size: Optional[int] = 512, min_size: int = 11) -> Optional[str]:
  5213. """
  5214. 处理 base64 图片的尺寸:
  5215. - 若 max_size 不为 None 且大于该值,则等比例缩放
  5216. - 若任意一边小于 min_size,则补充白边 (Padding)
  5217. """
  5218. try:
  5219. from PIL import Image
  5220. import io
  5221. import base64
  5222. # 解析 base64 数据
  5223. if not base64_url.startswith("data:"):
  5224. return None
  5225. header, data = base64_url.split(",", 1)
  5226. media_type = header.split(";")[0].split(":")[1] # image/png
  5227. # 解码图片
  5228. img_data = base64.b64decode(data)
  5229. img = Image.open(io.BytesIO(img_data))
  5230. width, height = img.size
  5231. needs_downscale = max_size is not None and (width > max_size or height > max_size)
  5232. needs_pad = width < min_size or height < min_size
  5233. # 尺寸正常,无需处理
  5234. if not needs_downscale and not needs_pad:
  5235. return base64_url
  5236. new_width, new_height = width, height
  5237. # 1. 降分辨率
  5238. if needs_downscale:
  5239. if width > height:
  5240. new_width = max_size
  5241. new_height = int(height * max_size / width)
  5242. else:
  5243. new_height = max_size
  5244. new_width = int(width * max_size / height)
  5245. if (new_width, new_height) != (width, height):
  5246. img_resized = img.resize((new_width, new_height), Image.Resampling.BILINEAR)
  5247. else:
  5248. img_resized = img
  5249. # 2. 补齐白边 (Padding)
  5250. pad_width = max(new_width, min_size)
  5251. pad_height = max(new_height, min_size)
  5252. if pad_width > new_width or pad_height > new_height:
  5253. # 创建白色背景
  5254. padded_img = Image.new("RGBA" if img_resized.mode in ("RGBA", "P") else "RGB", (pad_width, pad_height), (255, 255, 255, 255))
  5255. offset_x = (pad_width - new_width) // 2
  5256. offset_y = (pad_height - new_height) // 2
  5257. padded_img.paste(img_resized, (offset_x, offset_y))
  5258. img_resized = padded_img
  5259. # 转换为 RGB(JPEG不支持 RGBA, P 等具有透明度或索引的模式)
  5260. if img_resized.mode != "RGB":
  5261. if img_resized.mode == "RGBA" or img_resized.mode == "P":
  5262. # Create a white background for transparent images
  5263. background = Image.new("RGB", img_resized.size, (255, 255, 255))
  5264. if img_resized.mode == "P" and "transparency" in img_resized.info:
  5265. img_resized = img_resized.convert("RGBA")
  5266. if img_resized.mode == "RGBA":
  5267. background.paste(img_resized, mask=img_resized.split()[3])
  5268. img_resized = background
  5269. img_resized = img_resized.convert("RGB")
  5270. # 重新编码为 JPEG(如果只是补齐没有缩放,可以稍微保留高点质量)
  5271. buffer = io.BytesIO()
  5272. quality = 60 if needs_downscale else 85
  5273. img_resized.save(buffer, format="JPEG", quality=quality, optimize=False)
  5274. new_data = base64.b64encode(buffer.getvalue()).decode("utf-8")
  5275. return f"data:image/jpeg;base64,{new_data}"
  5276. except Exception as e:
  5277. self.log.warning(f"[Image Process] 处理图片尺寸失败: {e}")
  5278. return None
  5279. async def _generate_image_description(
  5280. self,
  5281. image_url: str,
  5282. current_model: str,
  5283. *,
  5284. trace_id: Optional[str] = None,
  5285. ) -> str:
  5286. """
  5287. 使用小模型生成图片的文本描述
  5288. Args:
  5289. image_url: 图片 URL(base64 或 http(s))
  5290. current_model: 当前使用的模型
  5291. Returns:
  5292. 图片描述文本
  5293. """
  5294. try:
  5295. # 使用 qwen-vl-max(通义千问视觉模型)生成描述
  5296. # 注意:qwen-vl 系列专门支持视觉输入
  5297. description_model = "qwen-vl-max"
  5298. # 构建描述请求
  5299. messages = [
  5300. {
  5301. "role": "user",
  5302. "content": [
  5303. {
  5304. "type": "image_url",
  5305. "image_url": {"url": image_url}
  5306. },
  5307. {
  5308. "type": "text",
  5309. "text": "请用 1-2 句话简洁描述这张图片的主要内容。"
  5310. }
  5311. ]
  5312. }
  5313. ]
  5314. # 调用 LLM
  5315. call_kwargs = {
  5316. "messages": messages,
  5317. "model": description_model,
  5318. "tools": None,
  5319. "temperature": 0.3,
  5320. }
  5321. result = (
  5322. await self.call_recursive_llm(
  5323. trace_id,
  5324. purpose="ordinary",
  5325. fail_on_post_response_exhaustion=True,
  5326. **call_kwargs,
  5327. )
  5328. if trace_id
  5329. else await self.llm_call(**call_kwargs)
  5330. )
  5331. description = result.get("content", "").strip()
  5332. return description if description else "图片内容"
  5333. except (ResourceBudgetExceeded, ResourceBudgetStateError):
  5334. raise
  5335. except Exception as e:
  5336. self.log.warning(f"[Image Description] 生成描述失败: {e}")
  5337. return "图片内容"
  5338. def _add_cache_control(
  5339. self,
  5340. messages: List[Dict],
  5341. model: str,
  5342. enable: bool
  5343. ) -> List[Dict]:
  5344. """
  5345. 为支持的模型添加 Prompt Caching 标记
  5346. 策略:固定位置 + 延迟缓存
  5347. 1. 如果有未处理的图片(最后一条 assistant 之后的 tool messages 中有图片),跳过缓存
  5348. 2. system message 添加缓存(如果足够长)
  5349. 3. 固定位置缓存点(20, 40, 60, 80),确保每个缓存点间隔 >= 1024 tokens
  5350. 4. 最多使用 4 个缓存点(含 system)
  5351. Args:
  5352. messages: 原始消息列表
  5353. model: 模型名称
  5354. enable: 是否启用缓存
  5355. Returns:
  5356. 添加了 cache_control 的消息列表(深拷贝)
  5357. """
  5358. if not enable:
  5359. return messages
  5360. # 只对 Claude 模型启用
  5361. if "claude" not in model.lower():
  5362. return messages
  5363. # 延迟缓存:检查是否有未处理的图片
  5364. last_assistant_idx = -1
  5365. for i in range(len(messages) - 1, -1, -1):
  5366. if messages[i].get("role") == "assistant":
  5367. last_assistant_idx = i
  5368. break
  5369. # 检查最后一条 assistant 之后是否有包含图片的 tool messages
  5370. has_unprocessed_images = False
  5371. if last_assistant_idx >= 0:
  5372. for i in range(last_assistant_idx + 1, len(messages)):
  5373. msg = messages[i]
  5374. if msg.get("role") == "tool":
  5375. content = msg.get("content")
  5376. if isinstance(content, list):
  5377. has_unprocessed_images = any(
  5378. isinstance(block, dict) and block.get("type") == "image_url"
  5379. for block in content
  5380. )
  5381. if has_unprocessed_images:
  5382. break
  5383. if has_unprocessed_images:
  5384. self.log.debug("[Cache] 检测到未处理的图片,延迟缓存建立")
  5385. return messages
  5386. # 深拷贝避免修改原始数据
  5387. import copy
  5388. messages = copy.deepcopy(messages)
  5389. # 策略 1: 为 system message 添加缓存
  5390. system_cached = False
  5391. for msg in messages:
  5392. if msg.get("role") == "system":
  5393. content = msg.get("content", "")
  5394. if isinstance(content, str) and len(content) > 1000:
  5395. msg["content"] = [{
  5396. "type": "text",
  5397. "text": content,
  5398. "cache_control": {"type": "ephemeral"}
  5399. }]
  5400. system_cached = True
  5401. self.log.debug(f"[Cache] 为 system message 添加缓存标记 (len={len(content)})")
  5402. break
  5403. # 策略 2: 固定位置缓存点
  5404. CACHE_INTERVAL = 20
  5405. MAX_POINTS = 3 if system_cached else 4
  5406. MIN_TOKENS = 1024
  5407. AVG_TOKENS_PER_MSG = 70
  5408. total_msgs = len(messages)
  5409. if total_msgs == 0:
  5410. return messages
  5411. cache_positions = []
  5412. last_cache_pos = 0
  5413. for i in range(1, MAX_POINTS + 1):
  5414. target_pos = i * CACHE_INTERVAL - 1 # 19, 39, 59, 79
  5415. if target_pos >= total_msgs:
  5416. break
  5417. # 从目标位置开始查找合适的 user/assistant 消息
  5418. for j in range(target_pos, total_msgs):
  5419. msg = messages[j]
  5420. if msg.get("role") not in ("user", "assistant"):
  5421. continue
  5422. content = msg.get("content", "")
  5423. if not content:
  5424. continue
  5425. # 检查 content 是否非空
  5426. is_valid = False
  5427. if isinstance(content, str):
  5428. is_valid = len(content) > 0
  5429. elif isinstance(content, list):
  5430. is_valid = any(
  5431. isinstance(block, dict) and
  5432. block.get("type") == "text" and
  5433. len(block.get("text", "")) > 0
  5434. for block in content
  5435. )
  5436. if not is_valid:
  5437. continue
  5438. # 检查 token 距离
  5439. msg_count = j - last_cache_pos
  5440. estimated_tokens = msg_count * AVG_TOKENS_PER_MSG
  5441. if estimated_tokens >= MIN_TOKENS:
  5442. cache_positions.append(j)
  5443. last_cache_pos = j
  5444. self.log.debug(f"[Cache] 在位置 {j} 添加缓存点 (估算 {estimated_tokens} tokens)")
  5445. break
  5446. # 应用缓存标记
  5447. for idx in cache_positions:
  5448. msg = messages[idx]
  5449. content = msg.get("content", "")
  5450. if isinstance(content, str):
  5451. msg["content"] = [{
  5452. "type": "text",
  5453. "text": content,
  5454. "cache_control": {"type": "ephemeral"}
  5455. }]
  5456. self.log.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  5457. elif isinstance(content, list):
  5458. # 在最后一个 text block 添加 cache_control
  5459. for block in reversed(content):
  5460. if isinstance(block, dict) and block.get("type") == "text":
  5461. block["cache_control"] = {"type": "ephemeral"}
  5462. self.log.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  5463. break
  5464. self.log.debug(
  5465. f"[Cache] 总消息: {total_msgs}, "
  5466. f"缓存点: {len(cache_positions)} at {cache_positions}"
  5467. )
  5468. return messages
  5469. def _get_configured_tool_names(
  5470. self,
  5471. tools: Optional[List[str]] = None,
  5472. tool_groups: Optional[List[str]] = None,
  5473. exclude_tools: Optional[List[str]] = None,
  5474. ) -> set[str]:
  5475. """解析 RunConfig 的基础工具能力集合。"""
  5476. if tools is not None:
  5477. # Explicit tools are an exact capability set, not an addition to
  5478. # the default groups.
  5479. tool_names = set(tools)
  5480. elif tool_groups is not None:
  5481. tool_names = set(self.tools.get_tool_names(groups=tool_groups))
  5482. else:
  5483. tool_names = set(self.tools.get_tool_names())
  5484. if exclude_tools:
  5485. tool_names -= set(exclude_tools)
  5486. return tool_names
  5487. def _get_tool_schemas(
  5488. self,
  5489. tools: Optional[List[str]] = None,
  5490. tool_groups: Optional[List[str]] = None,
  5491. exclude_tools: Optional[List[str]] = None,
  5492. ) -> List[Dict]:
  5493. """获取 RunConfig 基础能力对应的工具 Schema。"""
  5494. tool_names = self._get_configured_tool_names(
  5495. tools,
  5496. tool_groups,
  5497. exclude_tools,
  5498. )
  5499. return self.tools.get_schemas(list(tool_names))
  5500. def _get_runtime_tool_names(
  5501. self,
  5502. config: RunConfig,
  5503. trace: Trace,
  5504. *,
  5505. in_side_branch: bool = False,
  5506. ) -> set[str]:
  5507. """在 RunConfig 基础能力上应用 Recursive 协议状态门禁。
  5508. 主循环每轮调用,使待审核、待执行与报告阶段只暴露当前允许的工具。
  5509. """
  5510. tool_names = self._get_configured_tool_names(
  5511. config.tools,
  5512. config.tool_groups,
  5513. config.exclude_tools,
  5514. )
  5515. policy = policy_from_context(trace.context)
  5516. protocol_tools = {
  5517. "submit_task_report",
  5518. "review_task_result",
  5519. "update_task_progress",
  5520. "read_context_ref",
  5521. "manage_candidate",
  5522. }
  5523. if not policy.requires_task_protocol or in_side_branch:
  5524. available = tool_names - protocol_tools
  5525. if policy.requires_task_protocol:
  5526. available.discard("evaluate")
  5527. return available
  5528. if self.application_binding is not None and trace.context.get(
  5529. "application_ref"
  5530. ):
  5531. role = self.application_binding.role(
  5532. trace.context.get("application_role_id")
  5533. )
  5534. limits = trace.context.get("effective_run_limits") or {}
  5535. depth = int(trace.context.get("agent_depth", 0) or 0)
  5536. if (
  5537. not role.role.allowed_child_roles
  5538. or depth >= int(limits.get("max_depth", policy.max_depth))
  5539. ):
  5540. tool_names.discard("agent")
  5541. state = ensure_task_protocol(trace.context)
  5542. tool_names.discard("evaluate")
  5543. if state["pending_reviews"]:
  5544. return tool_names & {"review_task_result", "read_context_ref"}
  5545. if state["next_actions"]:
  5546. return tool_names & {"agent", "read_context_ref"}
  5547. tool_names.discard("review_task_result")
  5548. if self.candidate_service is None or state.get("task_report") is not None:
  5549. tool_names.discard("manage_candidate")
  5550. if not policy.requires_task_progress or state.get("task_report") is not None:
  5551. tool_names.discard("update_task_progress")
  5552. if not trace.parent_trace_id or state.get("task_report") is not None:
  5553. tool_names.discard("submit_task_report")
  5554. return tool_names
  5555. def _get_runtime_tool_schemas(
  5556. self,
  5557. config: RunConfig,
  5558. trace: Trace,
  5559. *,
  5560. in_side_branch: bool = False,
  5561. runtime_tool_names: Optional[set[str]] = None,
  5562. ) -> List[Dict]:
  5563. """按 Trace 持久化模式和当前协议状态生成工具 Schema。
  5564. 主循环把结果交给 LLM;Structured Recursive 只允许受治理的本地
  5565. ``task_brief`` 委托,Legacy 和 Recursive revision 1 继续使用 ``task``。
  5566. """
  5567. tool_names = (
  5568. runtime_tool_names
  5569. if runtime_tool_names is not None
  5570. else self._get_runtime_tool_names(
  5571. config,
  5572. trace,
  5573. in_side_branch=in_side_branch,
  5574. )
  5575. )
  5576. schemas = deepcopy(self.tools.get_schemas(list(tool_names)))
  5577. policy = policy_from_context(trace.context)
  5578. for schema in schemas:
  5579. function = schema.get("function", {})
  5580. if function.get("name") != "agent":
  5581. continue
  5582. parameters = function.get("parameters", {})
  5583. properties = parameters.get("properties", {})
  5584. required = parameters.setdefault("required", [])
  5585. if policy.requires_task_protocol:
  5586. properties.pop("messages", None)
  5587. properties.pop("task", None)
  5588. if "task_brief" in properties:
  5589. properties["task_brief"]["description"] = (
  5590. "Required structured contract for Recursive local delegation. "
  5591. "remote_* agents are not supported in Recursive revision 3."
  5592. )
  5593. if "task" in required:
  5594. required.remove("task")
  5595. if "task_brief" in properties and "task_brief" not in required:
  5596. required.append("task_brief")
  5597. if self.application_binding is not None and trace.context.get(
  5598. "application_ref"
  5599. ):
  5600. role = self.application_binding.role(
  5601. trace.context.get("application_role_id")
  5602. )
  5603. properties.pop("skills", None)
  5604. if "skills" in required:
  5605. required.remove("skills")
  5606. if "agent_type" in properties:
  5607. properties["agent_type"]["enum"] = list(
  5608. role.role.allowed_child_roles
  5609. )
  5610. properties["agent_type"]["description"] = (
  5611. "Required application role for the direct child."
  5612. )
  5613. if "agent_type" not in required:
  5614. required.append("agent_type")
  5615. else:
  5616. properties.pop("task_brief", None)
  5617. if "task" in properties and "task" not in required:
  5618. required.append("task")
  5619. return schemas
  5620. def _build_tool_context(
  5621. self,
  5622. *,
  5623. config: RunConfig,
  5624. trace: Trace,
  5625. trace_id: str,
  5626. goal_id: Optional[str],
  5627. goal_tree: Optional[GoalTree],
  5628. sequence: int,
  5629. head_sequence: int | None = None,
  5630. side_branch_ctx: Optional[SideBranchContext],
  5631. trigger_event: Optional[str],
  5632. tool_call_id: str | None = None,
  5633. ) -> Dict[str, Any]:
  5634. """构建 ToolRegistry 执行时注入的隐藏上下文。
  5635. 主循环在 dispatch 前调用;Recursive 权限快照和调度配置最后覆盖,不可伪造。
  5636. """
  5637. framework_context = {
  5638. "store": self.trace_store,
  5639. "task_protocol_service": self.task_protocol_service,
  5640. "candidate_service": self.candidate_service,
  5641. "event_service": self.event_service,
  5642. "trace_id": trace_id,
  5643. "goal_id": goal_id,
  5644. "runner": self,
  5645. "goal_tree": goal_tree,
  5646. "knowledge_config": config.knowledge,
  5647. "memory_config": config.memory,
  5648. "dream_scope": (
  5649. DreamScope(
  5650. uid=trace.uid,
  5651. agent_type=trace.agent_type or config.agent_type,
  5652. memory_identity=compute_memory_identity(config.memory),
  5653. )
  5654. if config.memory is not None
  5655. else None
  5656. ),
  5657. "sequence": sequence,
  5658. "head_sequence": head_sequence,
  5659. "tool_call_id": tool_call_id,
  5660. "side_branch": {
  5661. "type": side_branch_ctx.type,
  5662. "branch_id": side_branch_ctx.branch_id,
  5663. "is_side_branch": True,
  5664. "max_turns": side_branch_ctx.max_turns,
  5665. "trigger_event": trigger_event,
  5666. } if side_branch_ctx else None,
  5667. }
  5668. if policy_from_context(trace.context).mode is AgentMode.RECURSIVE:
  5669. context = {**(config.context or {}), **framework_context}
  5670. context.update({
  5671. RECURSIVE_CAPABILITY_TOOLS_CONTEXT_KEY: sorted(
  5672. self._get_configured_tool_names(
  5673. config.tools,
  5674. config.tool_groups,
  5675. config.exclude_tools,
  5676. )
  5677. ),
  5678. RECURSIVE_CHILD_EXECUTION_MODE_CONTEXT_KEY: config.child_execution_mode,
  5679. RECURSIVE_MAX_PARALLEL_CHILDREN_CONTEXT_KEY: config.max_parallel_children,
  5680. })
  5681. return context
  5682. # Framework-owned hidden values are authoritative in every mode. A
  5683. # caller-provided custom context may add page/business metadata, but it
  5684. # cannot replace the store, Trace identity or per-run MemoryConfig.
  5685. return {**(config.context or {}), **framework_context}
  5686. # 默认 system prompt 前缀(当 config.system_prompt 和前端都未提供 system message 时使用)
  5687. # 注意:此常量已迁移到 cyber_agent.core.prompts,这里保留引用以保持向后兼容
  5688. async def _build_system_prompt(self, config: RunConfig, base_prompt: Optional[str] = None) -> Optional[str]:
  5689. """构建 system prompt(注入 skills)
  5690. 优先级:
  5691. 1. base_prompt(来自消息)
  5692. 2. config.system_prompt(显式指定)
  5693. 3. preset.system_prompt(预设的完整 system prompt)
  5694. 4. 默认模板 + skills
  5695. Skills 注入优先级:
  5696. 1. config.skills 显式指定 → 按名称过滤
  5697. 2. config.skills 为 None → 查 preset 的默认 skills 列表
  5698. 3. preset 也无 skills(None)→ 加载全部(向后兼容)
  5699. Args:
  5700. base_prompt: 已有 system 内容(来自消息),
  5701. None 时使用 config.system_prompt 或 preset.system_prompt
  5702. """
  5703. from cyber_agent.core.presets import AGENT_PRESETS
  5704. # 确定 system_prompt 来源
  5705. if base_prompt is not None:
  5706. system_prompt = base_prompt
  5707. elif config.system_prompt is not None:
  5708. system_prompt = config.system_prompt
  5709. else:
  5710. # 尝试从 preset 获取 system_prompt
  5711. preset = AGENT_PRESETS.get(config.agent_type)
  5712. system_prompt = preset.system_prompt if preset and preset.system_prompt else None
  5713. # 确定要加载哪些 skills
  5714. skills_filter: Optional[List[str]] = config.skills
  5715. if skills_filter is None:
  5716. preset = AGENT_PRESETS.get(config.agent_type)
  5717. if preset is not None:
  5718. skills_filter = preset.skills # 可能仍为 None(加载全部)
  5719. # 加载并过滤
  5720. all_skills = load_skills_from_dir(self.skills_dir)
  5721. if skills_filter is not None:
  5722. skills = [s for s in all_skills if s.name in skills_filter]
  5723. else:
  5724. skills = all_skills
  5725. skills_text = self._format_skills(skills) if skills else ""
  5726. if system_prompt:
  5727. if skills_text:
  5728. system_prompt += f"\n\n## Skills\n{skills_text}"
  5729. else:
  5730. system_prompt = DEFAULT_SYSTEM_PREFIX
  5731. if skills_text:
  5732. system_prompt += f"\n\n## Skills\n{skills_text}"
  5733. if config.max_iterations and config.max_iterations > 0:
  5734. system_prompt += f"\n\n## Execution Constraint\n这是一项有严格步数限制的任务。你最多可以用 {config.max_iterations} 轮交互来解决问题。\n请务必【边查边写、随时存档】!每当你收集或得出一个有价值的独立结果(如收集到一个独立 Case),请立刻调用工具写入或追加到结果文件中,绝对不要等到所有任务都做完再最后一次性输出。这样即使触达步数上限被强制打断,你已经收集的成果也能安全保留!"
  5735. # Memory 注入(memory-bearing Agent)——在 system prompt 末尾追加
  5736. # 初版选择 system prompt 追加(见 cyber_agent/docs/framework/runtime/memory.md 待定问题 1)。
  5737. # 好处:run 启动一次性注入、所有后续轮次都能看到、与 skills 注入方式一致。
  5738. # 代价:若记忆文件很大会持续占 prompt tokens —— 待观察后决定是否切换方案。
  5739. if config.memory:
  5740. try:
  5741. from cyber_agent.core.memory import load_memory_files, format_memory_injection
  5742. files = load_memory_files(config.memory)
  5743. memory_text = format_memory_injection(files)
  5744. if memory_text:
  5745. system_prompt += f"\n\n{memory_text}"
  5746. except Exception as e:
  5747. self.log.warning(f"[Memory] 加载记忆失败,跳过注入: {e}")
  5748. return system_prompt
  5749. @staticmethod
  5750. def _task_text(messages: List[Dict]) -> str:
  5751. """Extract the same plain task text used by Legacy title generation."""
  5752. text_parts = []
  5753. for msg in messages:
  5754. content = msg.get("content", "")
  5755. if isinstance(content, str):
  5756. text_parts.append(content)
  5757. elif isinstance(content, list):
  5758. for part in content:
  5759. if isinstance(part, dict) and part.get("type") == "text":
  5760. text_parts.append(part.get("text", ""))
  5761. return " ".join(text_parts).strip()
  5762. @classmethod
  5763. def _fallback_task_name(cls, messages: List[Dict]) -> str:
  5764. """Build a deterministic title without spending an untracked LLM call."""
  5765. raw_text = cls._task_text(messages)
  5766. if not raw_text:
  5767. return TASK_NAME_FALLBACK
  5768. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  5769. async def _generate_task_name(self, messages: List[Dict]) -> str:
  5770. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  5771. fallback = self._fallback_task_name(messages)
  5772. raw_text = self._task_text(messages)
  5773. # 尝试使用 utility_llm 生成标题
  5774. if self.utility_llm_call:
  5775. try:
  5776. result = await self.utility_llm_call(
  5777. messages=[
  5778. {"role": "system", "content": TASK_NAME_GENERATION_SYSTEM_PROMPT},
  5779. {"role": "user", "content": raw_text[:2000]},
  5780. ],
  5781. model="gpt-4o-mini", # 使用便宜模型
  5782. )
  5783. title = result.get("content", "").strip()
  5784. if title and len(title) < 100:
  5785. return title
  5786. except Exception:
  5787. pass
  5788. # Fallback: 截取前 50 字符
  5789. return fallback
  5790. def _format_skills(self, skills: List[Skill]) -> str:
  5791. if not skills:
  5792. return ""
  5793. return "\n\n".join(s.to_prompt_text() for s in skills)