runner.py 259 KB

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