runner.py 248 KB

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