runner.py 248 KB

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