runner.py 222 KB

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