runner.py 248 KB

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