runner.py 196 KB

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