runner.py 180 KB

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