runner.py 184 KB

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