runner.py 178 KB

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