runner.py 227 KB

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