-
-
Notifications
You must be signed in to change notification settings - Fork 847
Expand file tree
/
Copy pathagent_tasks.py
More file actions
3588 lines (3057 loc) · 145 KB
/
Copy pathagent_tasks.py
File metadata and controls
3588 lines (3057 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DeepAudit Agent 审计任务 API
基于 LangGraph 的 Agent 审计
"""
import asyncio
import json
import logging
import os
import re
import zipfile
import shutil
from typing import Any, List, Optional, Dict, Set
from datetime import datetime, timezone
from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import case
from sqlalchemy.future import select
from sqlalchemy.orm import selectinload
from pydantic import BaseModel, Field
from app.api import deps
from app.db.session import get_db, async_session_factory
from app.models.agent_task import (
AgentTask, AgentEvent, AgentFinding,
AgentTaskStatus, AgentTaskPhase, AgentEventType,
VulnerabilitySeverity, FindingStatus,
)
from app.models.project import Project
from app.models.user import User
from app.models.user_config import UserConfig
from app.services.agent.event_manager import EventManager
from app.services.agent.streaming import StreamHandler, StreamEvent, StreamEventType
from app.services.git_ssh_service import GitSSHOperations
from app.core.encryption import decrypt_sensitive_data
logger = logging.getLogger(__name__)
router = APIRouter()
# 运行中的任务(兼容旧接口)
_running_tasks: Dict[str, Any] = {}
# 🔥 运行中的 asyncio Tasks(用于强制取消)
_running_asyncio_tasks: Dict[str, asyncio.Task] = {}
# ============ Schemas ============
class AgentTaskCreate(BaseModel):
"""创建 Agent 任务请求"""
project_id: str = Field(..., description="项目 ID")
name: Optional[str] = Field(None, description="任务名称")
description: Optional[str] = Field(None, description="任务描述")
# 审计配置
audit_scope: Optional[dict] = Field(None, description="审计范围")
target_vulnerabilities: Optional[List[str]] = Field(
default=["sql_injection", "xss", "command_injection", "path_traversal", "ssrf"],
description="目标漏洞类型"
)
verification_level: str = Field(
"sandbox",
description="验证级别: analysis_only, sandbox, generate_poc"
)
# 分支
branch_name: Optional[str] = Field(None, description="分支名称")
# 排除模式
exclude_patterns: Optional[List[str]] = Field(
default=["node_modules", "__pycache__", ".git", "*.min.js"],
description="排除模式"
)
# 文件范围
target_files: Optional[List[str]] = Field(None, description="指定扫描的文件")
# Agent 配置
max_iterations: int = Field(50, ge=1, le=200, description="最大迭代次数")
timeout_seconds: int = Field(1800, ge=60, le=7200, description="超时时间(秒)")
class AgentTaskResponse(BaseModel):
"""Agent 任务响应 - 包含所有前端需要的字段"""
id: str
project_id: str
name: Optional[str]
description: Optional[str]
task_type: str = "agent_audit"
status: str
current_phase: Optional[str]
current_step: Optional[str] = None
# 进度统计
total_files: int = 0
indexed_files: int = 0
analyzed_files: int = 0
total_chunks: int = 0
# Agent 统计
total_iterations: int = 0
tool_calls_count: int = 0
tokens_used: int = 0
# 发现统计(兼容两种命名)
findings_count: int = 0
total_findings: int = 0 # 兼容字段
verified_count: int = 0
verified_findings: int = 0 # 兼容字段
false_positive_count: int = 0
# 严重程度统计
critical_count: int = 0
high_count: int = 0
medium_count: int = 0
low_count: int = 0
# 评分
quality_score: float = 0.0
security_score: Optional[float] = None
# 进度百分比
progress_percentage: float = 0.0
# 时间
created_at: datetime
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
# 配置
audit_scope: Optional[dict] = None
target_vulnerabilities: Optional[List[str]] = None
verification_level: Optional[str] = None
exclude_patterns: Optional[List[str]] = None
target_files: Optional[List[str]] = None
# 错误信息
error_message: Optional[str] = None
class Config:
from_attributes = True
class AgentEventResponse(BaseModel):
"""Agent 事件响应"""
id: str
task_id: str
event_type: str
phase: Optional[str]
message: Optional[str] = None
sequence: int
# 🔥 ORM 字段名是 created_at,序列化为 timestamp
created_at: datetime = Field(serialization_alias="timestamp")
# 工具相关字段
tool_name: Optional[str] = None
tool_input: Optional[Dict[str, Any]] = None
tool_output: Optional[Dict[str, Any]] = None
tool_duration_ms: Optional[int] = None
# 其他字段
progress_percent: Optional[float] = None
finding_id: Optional[str] = None
tokens_used: Optional[int] = None
# 🔥 ORM 字段名是 event_metadata,序列化为 metadata
event_metadata: Optional[Dict[str, Any]] = Field(default=None, serialization_alias="metadata")
model_config = {
"from_attributes": True,
"populate_by_name": True,
"by_alias": True, # 🔥 关键:确保序列化时使用别名
}
class AgentFindingResponse(BaseModel):
"""Agent 发现响应"""
id: str
task_id: str
vulnerability_type: str
severity: str
title: str
description: Optional[str]
file_path: Optional[str]
line_start: Optional[int]
line_end: Optional[int]
code_snippet: Optional[str]
is_verified: bool
# 🔥 FIX: Map from ai_confidence in ORM, make Optional with default
confidence: Optional[float] = Field(default=0.5, validation_alias="ai_confidence")
status: str
suggestion: Optional[str] = None
verdict: Optional[str] = None
poc: Optional[dict] = None
created_at: datetime
model_config = {
"from_attributes": True,
"populate_by_name": True, # Allow both 'confidence' and 'ai_confidence'
}
class TaskSummaryResponse(BaseModel):
"""任务摘要响应"""
task_id: str
status: str
security_score: Optional[int]
total_findings: int
verified_findings: int
severity_distribution: Dict[str, int]
vulnerability_types: Dict[str, int]
duration_seconds: Optional[int]
phases_completed: List[str]
# ============ 后台任务执行 ============
# 运行中的动态执行器
_running_orchestrators: Dict[str, Any] = {}
# 运行中的事件管理器(用于 SSE 流)
_running_event_managers: Dict[str, EventManager] = {}
# 🔥 已取消的任务集合(用于前置操作的取消检查)
_cancelled_tasks: Set[str] = set()
def is_task_cancelled(task_id: str) -> bool:
"""检查任务是否已被取消"""
return task_id in _cancelled_tasks
async def _execute_agent_task(task_id: str):
"""
在后台执行 Agent 任务 - 使用动态 Agent 树架构
架构:OrchestratorAgent 作为大脑,动态调度子 Agent
"""
from app.services.agent.agents import OrchestratorAgent, ReconAgent, AnalysisAgent, VerificationAgent
from app.services.agent.event_manager import EventManager, AgentEventEmitter
from app.services.llm.service import LLMService
from app.services.agent.core import agent_registry
from app.services.agent.tools import SandboxManager
from app.core.config import settings
import time
# 🔥 在任务最开始就初始化 Docker 沙箱管理器
# 这样可以确保整个任务生命周期内使用同一个管理器,并且尽早发现 Docker 问题
logger.info(f"🚀 Starting execution for task {task_id}")
sandbox_manager = SandboxManager()
await sandbox_manager.initialize()
logger.info(f"🐳 Global Sandbox Manager initialized (Available: {sandbox_manager.is_available})")
# 🔥 提前创建事件管理器,以便在克隆仓库和索引时发送实时日志
from app.services.agent.event_manager import EventManager, AgentEventEmitter
event_manager = EventManager(db_session_factory=async_session_factory)
event_manager.create_queue(task_id)
event_emitter = AgentEventEmitter(task_id, event_manager)
_running_event_managers[task_id] = event_manager
async with async_session_factory() as db:
orchestrator = None
start_time = time.time()
try:
# 获取任务
task = await db.get(AgentTask, task_id, options=[selectinload(AgentTask.project)])
if not task:
logger.error(f"Task {task_id} not found")
return
# 获取项目
project = task.project
if not project:
logger.error(f"Project not found for task {task_id}")
return
# 🔥 发送任务开始事件 - 使用 phase_start 让前端知道进入准备阶段
await event_emitter.emit_phase_start("preparation", f"🚀 任务开始执行: {project.name}")
# 更新任务阶段为准备中
task.status = AgentTaskStatus.RUNNING
task.started_at = datetime.now(timezone.utc)
task.current_phase = AgentTaskPhase.PLANNING # preparation 对应 PLANNING
await db.commit()
# 获取用户配置(需要在获取项目根目录之前,以便传递 token)
user_config = await _get_user_config(db, task.created_by)
# 从用户配置中提取 token和SSH密钥(用于私有仓库克隆)
other_config = (user_config or {}).get('otherConfig', {})
github_token = other_config.get('githubToken') or settings.GITHUB_TOKEN
gitlab_token = other_config.get('gitlabToken') or settings.GITLAB_TOKEN
gitea_token = other_config.get('giteaToken') or settings.GITEA_TOKEN
# 解密SSH私钥
ssh_private_key = None
if 'sshPrivateKey' in other_config:
try:
encrypted_key = other_config['sshPrivateKey']
ssh_private_key = decrypt_sensitive_data(encrypted_key)
logger.info("成功解密SSH私钥")
except Exception as e:
logger.warning(f"解密SSH私钥失败: {e}")
# 获取项目根目录(传递任务指定的分支和认证 token/SSH密钥)
# 🔥 传递 event_emitter 以发送克隆进度
project_root = await _get_project_root(
project,
task_id,
task.branch_name,
github_token=github_token,
gitlab_token=gitlab_token,
gitea_token=gitea_token, # 🔥 新增
ssh_private_key=ssh_private_key, # 🔥 新增SSH密钥
event_emitter=event_emitter, # 🔥 新增
)
# 🔥 自动修正 target_files 路径
# 如果发生了目录调整(例如 ZIP 解压后只有一层目录,root 被下移),
# 原有的 target_files (如 "Prefix/file.php") 可能无法匹配。
# 我们需要检测并移除这些无效的前缀。
if task.target_files and len(task.target_files) > 0:
# 1. 检查是否存在不匹配的文件
all_exist = True
for tf in task.target_files:
if not os.path.exists(os.path.join(project_root, tf)):
all_exist = False
break
if not all_exist:
logger.info(f"Target files path mismatch detected in {project_root}")
# 尝试通过路径匹配来修复
# 获取当前根目录的名称
root_name = os.path.basename(project_root)
new_target_files = []
fixed_count = 0
for tf in task.target_files:
# 检查文件是否以 root_name 开头(例如 "PHP-Project/index.php" 而 root 是 ".../PHP-Project")
if tf.startswith(root_name + "/"):
fixed_path = tf[len(root_name)+1:]
if os.path.exists(os.path.join(project_root, fixed_path)):
new_target_files.append(fixed_path)
fixed_count += 1
continue
# 如果上面的没匹配,尝试暴力搜索(只针对未找到的文件)
# 这种情况比较少见,先保留原样或标记为丢失
if os.path.exists(os.path.join(project_root, tf)):
new_target_files.append(tf)
else:
# 尝试查看 tf 的 basename 是否在根目录直接存在(针对常见的最简情况)
basename = os.path.basename(tf)
if os.path.exists(os.path.join(project_root, basename)):
new_target_files.append(basename)
fixed_count += 1
else:
# 实在找不到,保留原样,让后续流程报错或忽略
new_target_files.append(tf)
if fixed_count > 0:
logger.info(f"🔧 Auto-fixed {fixed_count} target file paths")
await event_emitter.emit_info(f"🔧 自动修正了 {fixed_count} 个目标文件的路径")
task.target_files = new_target_files
# 🔥 重新验证修正后的文件
valid_target_files = []
if task.target_files:
for tf in task.target_files:
if os.path.exists(os.path.join(project_root, tf)):
valid_target_files.append(tf)
else:
logger.warning(f"⚠️ Target file not found: {tf}")
if not valid_target_files:
logger.warning("❌ No valid target files found after adjustment!")
await event_emitter.emit_warning("⚠️ 警告:无法找到指定的目标文件,将扫描所有文件")
task.target_files = None # 回退到全量扫描
elif len(valid_target_files) < len(task.target_files):
logger.warning(f"⚠️ Partial target files missing. Found {len(valid_target_files)}/{len(task.target_files)}")
task.target_files = valid_target_files
logger.info(f"🚀 Task {task_id} started with Dynamic Agent Tree architecture")
# 🔥 获取项目根目录后检查取消
if is_task_cancelled(task_id):
logger.info(f"[Cancel] Task {task_id} cancelled after project preparation")
raise asyncio.CancelledError("任务已取消")
# 创建 LLM 服务
llm_service = LLMService(user_config=user_config)
# 初始化工具集 - 传递排除模式和目标文件以及预初始化的 sandbox_manager
# 🔥 传递 event_emitter 以发送索引进度,传递 task_id 以支持取消
tools = await _initialize_tools(
project_root,
llm_service,
user_config,
sandbox_manager=sandbox_manager,
exclude_patterns=task.exclude_patterns,
target_files=task.target_files,
project_id=str(project.id), # 🔥 传递 project_id 用于 RAG
event_emitter=event_emitter, # 🔥 新增
task_id=task_id, # 🔥 新增:用于取消检查
)
# 🔥 初始化工具后检查取消
if is_task_cancelled(task_id):
logger.info(f"[Cancel] Task {task_id} cancelled after tools initialization")
raise asyncio.CancelledError("任务已取消")
# 创建子 Agent
recon_agent = ReconAgent(
llm_service=llm_service,
tools=tools.get("recon", {}),
event_emitter=event_emitter,
)
analysis_agent = AnalysisAgent(
llm_service=llm_service,
tools=tools.get("analysis", {}),
event_emitter=event_emitter,
)
verification_agent = VerificationAgent(
llm_service=llm_service,
tools=tools.get("verification", {}),
event_emitter=event_emitter,
)
# 创建 Orchestrator Agent
orchestrator = OrchestratorAgent(
llm_service=llm_service,
tools=tools.get("orchestrator", {}),
event_emitter=event_emitter,
sub_agents={
"recon": recon_agent,
"analysis": analysis_agent,
"verification": verification_agent,
},
)
# 🔥 设置外部取消检查回调
# 这确保即使 runner.cancel() 失败,Agent 也能通过 checking 全局标志感知取消
def check_global_cancel():
return is_task_cancelled(task_id)
orchestrator.set_cancel_callback(check_global_cancel)
# 同时也为子 Agent 设置(虽然 Orchestrator 会传播)
recon_agent.set_cancel_callback(check_global_cancel)
analysis_agent.set_cancel_callback(check_global_cancel)
verification_agent.set_cancel_callback(check_global_cancel)
# 注册到全局
_running_orchestrators[task_id] = orchestrator
_running_tasks[task_id] = orchestrator # 兼容旧的取消逻辑
_running_event_managers[task_id] = event_manager # 用于 SSE 流
# 🔥 清理旧的 Agent 注册表,避免显示多个树
from app.services.agent.core import agent_registry
agent_registry.clear()
# 注册 Orchestrator 到 Agent Registry(使用其内置方法)
orchestrator._register_to_registry(task="Root orchestrator for security audit")
await event_emitter.emit_info("🧠 动态 Agent 树架构启动")
await event_emitter.emit_info(f"📁 项目路径: {project_root}")
# 收集项目信息 - 传递排除模式和目标文件
project_info = await _collect_project_info(
project_root,
project.name,
exclude_patterns=task.exclude_patterns,
target_files=task.target_files,
)
# 更新任务文件统计
task.total_files = project_info.get("file_count", 0)
await db.commit()
# 构建输入数据
input_data = {
"project_info": project_info,
"config": {
"target_vulnerabilities": task.target_vulnerabilities or [],
"verification_level": task.verification_level or "sandbox",
"exclude_patterns": task.exclude_patterns or [],
"target_files": task.target_files or [],
"max_iterations": task.max_iterations or 50,
},
"project_root": project_root,
"task_id": task_id,
}
# 执行 Orchestrator
await event_emitter.emit_phase_start("orchestration", "🎯 Orchestrator 开始编排审计流程")
task.current_phase = AgentTaskPhase.ANALYSIS
await db.commit()
# 🔥 将 orchestrator.run() 包装在 asyncio.Task 中,以便可以强制取消
run_task = asyncio.create_task(orchestrator.run(input_data))
_running_asyncio_tasks[task_id] = run_task
try:
result = await run_task
finally:
_running_asyncio_tasks.pop(task_id, None)
# 处理结果
duration_ms = int((time.time() - start_time) * 1000)
await db.refresh(task)
if result.success:
# 🔥 CRITICAL FIX: Log and save findings with detailed debugging
findings = result.data.get("findings", [])
logger.info(f"[AgentTask] Task {task_id} completed with {len(findings)} findings from Orchestrator")
# 🔥 Debug: Log each finding for verification
for i, f in enumerate(findings[:5]): # Log first 5
if isinstance(f, dict):
logger.debug(f"[AgentTask] Finding {i+1}: {f.get('title', 'N/A')[:50]} - {f.get('severity', 'N/A')}")
# 🔥 v2.1: 传递 project_root 用于文件路径验证
saved_count = await _save_findings(db, task_id, findings, project_root=project_root)
logger.info(f"[AgentTask] Saved {saved_count}/{len(findings)} findings (filtered {len(findings) - saved_count} hallucinations)")
# 更新任务统计
# 🔥 CRITICAL FIX: 在设置完成前再次检查取消状态
# 避免 "取消后后端继续运行并最终标记为完成" 的问题
if is_task_cancelled(task_id):
logger.info(f"[AgentTask] Task {task_id} was cancelled, overriding success result")
task.status = AgentTaskStatus.CANCELLED
else:
task.status = AgentTaskStatus.COMPLETED
task.completed_at = datetime.now(timezone.utc)
task.current_phase = AgentTaskPhase.REPORTING
task.findings_count = saved_count # 🔥 v2.1: 使用实际保存的数量(排除幻觉)
# 🔥 CRITICAL FIX: 累加所有子 Agent 的统计,而不仅仅是 Orchestrator 的
total_iterations = result.iterations
tool_calls_count = result.tool_calls
tokens_used = result.tokens_used
if hasattr(orchestrator, 'sub_agents'):
for agent in orchestrator.sub_agents.values():
if hasattr(agent, 'get_stats'):
sub_stats = agent.get_stats()
total_iterations += sub_stats.get("iterations", 0)
tool_calls_count += sub_stats.get("tool_calls", 0)
tokens_used += sub_stats.get("tokens_used", 0)
task.total_iterations = total_iterations
task.tool_calls_count = tool_calls_count
task.tokens_used = tokens_used
# 🔥 统计文件数量
# analyzed_files = 实际扫描过的文件数(任务完成时等于 total_files)
# files_with_findings = 有漏洞发现的唯一文件数
task.analyzed_files = task.total_files # Agent 扫描了所有符合条件的文件
# 🔥 FIX: 先过滤 findings,再用过滤后的列表做统计
# 与 _save_findings 的过滤逻辑保持一致(排除无 file_path 的 finding)
filtered_findings = []
files_with_findings_set = set()
for f in findings:
if isinstance(f, dict):
raw_file_path = f.get("file_path") or f.get("file")
file_path = raw_file_path if isinstance(raw_file_path, str) else ""
if not file_path:
raw_location = f.get("location", "")
location = raw_location if isinstance(raw_location, str) else ""
file_path = location.split(":")[0]
if file_path:
files_with_findings_set.add(file_path)
filtered_findings.append(f)
task.files_with_findings = len(files_with_findings_set)
# 统计严重程度和验证状态(使用过滤后的列表)
verified_count = 0
for f in filtered_findings:
sev = str(f.get("severity", "low")).lower()
if sev == "critical":
task.critical_count += 1
elif sev == "high":
task.high_count += 1
elif sev == "medium":
task.medium_count += 1
elif sev == "low":
task.low_count += 1
# 🔥 统计已验证的发现
if f.get("is_verified") or f.get("verdict") == "confirmed":
verified_count += 1
task.verified_count = verified_count
# 计算安全评分(使用过滤后的列表)
task.security_score = _calculate_security_score(filtered_findings)
task.quality_score = _calculate_security_score(filtered_findings)
# 🔥 注意: progress_percentage 是计算属性,不需要手动设置
# 当 status = COMPLETED 时会自动返回 100.0
await db.commit()
await event_emitter.emit_task_complete(
findings_count=len(findings),
duration_ms=duration_ms,
)
logger.info(f"✅ Task {task_id} completed: {len(findings)} findings, {duration_ms}ms")
else:
# 🔥 检查是否是取消导致的失败
if result.error == "任务已取消":
# 状态可能已经被 cancel API 更新,只需确保一致性
if task.status != AgentTaskStatus.CANCELLED:
task.status = AgentTaskStatus.CANCELLED
task.completed_at = datetime.now(timezone.utc)
await db.commit()
logger.info(f"🛑 Task {task_id} cancelled")
else:
task.status = AgentTaskStatus.FAILED
task.error_message = result.error or "Unknown error"
task.completed_at = datetime.now(timezone.utc)
await db.commit()
await event_emitter.emit_error(result.error or "Unknown error")
logger.error(f"❌ Task {task_id} failed: {result.error}")
except asyncio.CancelledError:
logger.info(f"Task {task_id} cancelled")
try:
task = await db.get(AgentTask, task_id)
if task:
task.status = AgentTaskStatus.CANCELLED
task.completed_at = datetime.now(timezone.utc)
await db.commit()
except Exception:
pass
except Exception as e:
logger.error(f"Task {task_id} failed: {e}", exc_info=True)
try:
task = await db.get(AgentTask, task_id)
if task:
task.status = AgentTaskStatus.FAILED
task.error_message = str(e)[:1000]
task.completed_at = datetime.now(timezone.utc)
await db.commit()
except Exception as db_error:
logger.error(f"Failed to update task status: {db_error}")
finally:
# 🔥 在清理之前保存 Agent 树到数据库
try:
async with async_session_factory() as save_db:
await _save_agent_tree(save_db, task_id)
except Exception as save_error:
logger.error(f"Failed to save agent tree: {save_error}")
# 清理
_running_orchestrators.pop(task_id, None)
_running_tasks.pop(task_id, None)
_running_event_managers.pop(task_id, None)
_running_asyncio_tasks.pop(task_id, None) # 🔥 清理 asyncio task
_cancelled_tasks.discard(task_id) # 🔥 清理取消标志
# 🔥 清理整个 Agent 注册表(包括所有子 Agent)
agent_registry.clear()
logger.debug(f"Task {task_id} cleaned up")
async def _get_user_config(db: AsyncSession, user_id: Optional[str]) -> Optional[Dict[str, Any]]:
"""获取用户配置"""
if not user_id:
return None
try:
from app.api.v1.endpoints.config import (
decrypt_config,
SENSITIVE_LLM_FIELDS, SENSITIVE_OTHER_FIELDS
)
result = await db.execute(
select(UserConfig).where(UserConfig.user_id == user_id)
)
config = result.scalar_one_or_none()
if config and config.llm_config:
user_llm_config = json.loads(config.llm_config) if config.llm_config else {}
user_other_config = json.loads(config.other_config) if config.other_config else {}
user_llm_config = decrypt_config(user_llm_config, SENSITIVE_LLM_FIELDS)
user_other_config = decrypt_config(user_other_config, SENSITIVE_OTHER_FIELDS)
return {
"llmConfig": user_llm_config,
"otherConfig": user_other_config,
}
except Exception as e:
logger.warning(f"Failed to get user config: {e}")
return None
async def _initialize_tools(
project_root: str,
llm_service,
user_config: Optional[Dict[str, Any]],
sandbox_manager: Any, # 传递预初始化的 SandboxManager
exclude_patterns: Optional[List[str]] = None,
target_files: Optional[List[str]] = None,
project_id: Optional[str] = None, # 🔥 用于 RAG collection_name
event_emitter: Optional[Any] = None, # 🔥 新增:用于发送实时日志
task_id: Optional[str] = None, # 🔥 新增:用于取消检查
) -> Dict[str, Dict[str, Any]]:
"""初始化工具集
Args:
project_root: 项目根目录
llm_service: LLM 服务
user_config: 用户配置
sandbox_manager: 沙箱管理器
exclude_patterns: 排除模式列表
target_files: 目标文件列表
project_id: 项目 ID(用于 RAG collection_name)
event_emitter: 事件发送器(用于发送实时日志)
task_id: 任务 ID(用于取消检查)
"""
from app.services.agent.tools import (
FileReadTool, FileSearchTool, ListFilesTool,
PatternMatchTool, CodeAnalysisTool, DataFlowAnalysisTool,
SemgrepTool, BanditTool, GitleaksTool,
NpmAuditTool, SafetyTool, TruffleHogTool, OSVScannerTool, # 🔥 Added missing tools
ThinkTool, ReflectTool,
CreateVulnerabilityReportTool,
VulnerabilityValidationTool,
# 🔥 RAG 工具
RAGQueryTool, SecurityCodeSearchTool, FunctionContextTool,
)
from app.services.agent.knowledge import (
SecurityKnowledgeQueryTool,
GetVulnerabilityKnowledgeTool,
)
# 🔥 RAG 相关导入
from app.services.rag import CodeIndexer, CodeRetriever, EmbeddingService, IndexUpdateMode
from app.core.config import settings
# 辅助函数:发送事件
async def emit(message: str, level: str = "info"):
if event_emitter:
logger.debug(f"[EMIT-TOOLS] Sending {level}: {message[:60]}...")
if level == "info":
await event_emitter.emit_info(message)
elif level == "warning":
await event_emitter.emit_warning(message)
elif level == "error":
await event_emitter.emit_error(message)
else:
logger.warning(f"[EMIT-TOOLS] No event_emitter, skipping: {message[:60]}...")
# ============ 🔥 初始化 RAG 系统 ============
retriever = None
try:
await emit(f"🔍 正在初始化 RAG 系统...")
# 从用户配置中获取 embedding 配置
user_llm_config = (user_config or {}).get('llmConfig', {})
user_other_config = (user_config or {}).get('otherConfig', {})
user_embedding_config = user_other_config.get('embedding_config', {})
# Embedding Provider 优先级:用户嵌入配置 > 环境变量
embedding_provider = (
user_embedding_config.get('provider') or
getattr(settings, 'EMBEDDING_PROVIDER', 'openai')
)
# Embedding Model 优先级:用户嵌入配置 > 环境变量
embedding_model = (
user_embedding_config.get('model') or
getattr(settings, 'EMBEDDING_MODEL', 'text-embedding-3-small')
)
# API Key 优先级:用户嵌入配置 > 环境变量 EMBEDDING_API_KEY > 用户 LLM 配置 > 环境变量 LLM_API_KEY
# 注意:API Key 可以共享,因为很多用户使用同一个 OpenAI Key 做 LLM 和 Embedding
embedding_api_key = (
user_embedding_config.get('api_key') or
getattr(settings, 'EMBEDDING_API_KEY', None) or
user_llm_config.get('llmApiKey') or
getattr(settings, 'LLM_API_KEY', '') or
''
)
# Base URL 优先级:用户嵌入配置 > 环境变量 EMBEDDING_BASE_URL > None(使用提供商默认地址)
# 🔥 重要:Base URL 不应该回退到 LLM 的 base_url,因为 Embedding 和 LLM 可能使用完全不同的服务
# 例如:LLM 使用 SiliconFlow,但 Embedding 使用 HuggingFace
embedding_base_url = (
user_embedding_config.get('base_url') or
getattr(settings, 'EMBEDDING_BASE_URL', None) or
None
)
logger.info(f"RAG 配置: provider={embedding_provider}, model={embedding_model}, base_url={embedding_base_url or '(使用默认)'}")
await emit(f"📊 Embedding 配置: {embedding_provider}/{embedding_model}")
# 创建 Embedding 服务
embedding_service = EmbeddingService(
provider=embedding_provider,
model=embedding_model,
api_key=embedding_api_key,
base_url=embedding_base_url,
)
# 使用用户配置的 batch_size
embedding_service.batch_size = user_embedding_config.get('batch_size', 100)
# 创建 collection_name(基于 project_id)
collection_name = f"project_{project_id}" if project_id else "default_project"
# 🔥 v2.0: 创建 CodeIndexer 并进行智能索引
# 智能索引会自动:
# - 检测 embedding 模型变更,如需要则自动重建
# - 对比文件 hash,只更新变化的文件(增量更新)
indexer = CodeIndexer(
collection_name=collection_name,
embedding_service=embedding_service,
persist_directory=settings.VECTOR_DB_PATH,
)
logger.info(f"📝 开始智能索引项目: {project_root}")
await emit(f"📝 正在构建代码向量索引...")
index_progress = None
last_progress_update = 0
last_embedding_progress = [0] # 使用列表以便在闭包中修改
embedding_total = [0] # 记录总数
# 🔥 嵌入进度回调函数(同步,但会调度异步任务)
def on_embedding_progress(processed: int, total: int):
embedding_total[0] = total
# 每处理 50 个或完成时更新
if processed - last_embedding_progress[0] >= 50 or processed == total:
last_embedding_progress[0] = processed
percentage = (processed / total * 100) if total > 0 else 0
msg = f"🔢 嵌入进度: {processed}/{total} ({percentage:.0f}%)"
logger.info(msg)
# 使用 asyncio.create_task 调度异步 emit
try:
loop = asyncio.get_running_loop()
loop.create_task(emit(msg))
except Exception as e:
logger.warning(f"Failed to emit embedding progress: {e}")
# 🔥 创建取消检查函数,用于在嵌入批处理中检查取消状态
def check_cancelled() -> bool:
return task_id is not None and is_task_cancelled(task_id)
async for progress in indexer.smart_index_directory(
directory=project_root,
exclude_patterns=exclude_patterns or [],
include_patterns=target_files, # 🔥 传递 target_files 限制索引范围
update_mode=IndexUpdateMode.SMART,
embedding_progress_callback=on_embedding_progress,
cancel_check=check_cancelled, # 🔥 传递取消检查函数
):
# 🔥 在索引过程中检查取消状态
if check_cancelled():
logger.info(f"[Cancel] RAG indexing cancelled for task {task_id}")
raise asyncio.CancelledError("任务已取消")
index_progress = progress
# 每处理 10 个文件或有重要变化时发送进度更新
if progress.processed_files - last_progress_update >= 10 or progress.processed_files == progress.total_files:
if progress.total_files > 0:
await emit(
f"📝 索引进度: {progress.processed_files}/{progress.total_files} 文件 "
f"({progress.progress_percentage:.0f}%)"
)
last_progress_update = progress.processed_files
# 🔥 发送状态消息(如嵌入向量生成进度)
if progress.status_message:
await emit(progress.status_message)
progress.status_message = "" # 清空已发送的消息
if index_progress:
summary = (
f"✅ 索引完成: 模式={index_progress.update_mode}, "
f"新增={index_progress.added_files}, "
f"更新={index_progress.updated_files}, "
f"删除={index_progress.deleted_files}, "
f"代码块={index_progress.indexed_chunks}"
)
logger.info(summary)
await emit(summary)
# 创建 CodeRetriever(用于搜索)
# 🔥 传递 api_key,用于自动适配 collection 的 embedding 配置
retriever = CodeRetriever(
collection_name=collection_name,
embedding_service=embedding_service,
persist_directory=settings.VECTOR_DB_PATH,
api_key=embedding_api_key, # 🔥 传递 api_key 以支持自动切换 embedding
)
logger.info(f"✅ RAG 系统初始化成功: collection={collection_name}")
await emit(f"✅ RAG 系统初始化成功")
except Exception as e:
logger.warning(f"⚠️ RAG 系统初始化失败: {e}")
await emit(f"⚠️ RAG 系统初始化失败: {e}", "warning")
import traceback
logger.debug(f"RAG 初始化异常详情:\n{traceback.format_exc()}")
retriever = None
# 基础工具 - 传递排除模式和目标文件
base_tools = {
"read_file": FileReadTool(project_root, exclude_patterns, target_files),
"list_files": ListFilesTool(project_root, exclude_patterns, target_files),
"search_code": FileSearchTool(project_root, exclude_patterns, target_files),
"think": ThinkTool(),
"reflect": ReflectTool(),
}
# Recon 工具
recon_tools = {
**base_tools,
# 🔥 外部侦察工具 (Recon 阶段也需要使用这些工具来收集初步信息)
"semgrep_scan": SemgrepTool(project_root, sandbox_manager),
"bandit_scan": BanditTool(project_root, sandbox_manager),
"gitleaks_scan": GitleaksTool(project_root, sandbox_manager),
"npm_audit": NpmAuditTool(project_root, sandbox_manager),
"safety_scan": SafetyTool(project_root, sandbox_manager),
"trufflehog_scan": TruffleHogTool(project_root, sandbox_manager),
"osv_scan": OSVScannerTool(project_root, sandbox_manager),
}
# 🔥 注册 RAG 工具到 Recon Agent
if retriever:
recon_tools["rag_query"] = RAGQueryTool(retriever)
logger.info("✅ RAG 工具 (rag_query) 已注册到 Recon Agent")
# Analysis 工具
# 🔥 导入智能扫描工具
from app.services.agent.tools import SmartScanTool, QuickAuditTool
analysis_tools = {
**base_tools,
# 🔥 智能扫描工具(推荐首先使用)
"smart_scan": SmartScanTool(project_root),
"quick_audit": QuickAuditTool(project_root),
# 模式匹配工具(增强版)
"pattern_match": PatternMatchTool(project_root),
# 数据流分析
"dataflow_analysis": DataFlowAnalysisTool(llm_service),
# 外部安全工具 (传入共享的 sandbox_manager)
"semgrep_scan": SemgrepTool(project_root, sandbox_manager),
"bandit_scan": BanditTool(project_root, sandbox_manager),
"gitleaks_scan": GitleaksTool(project_root, sandbox_manager),
"npm_audit": NpmAuditTool(project_root, sandbox_manager),
"safety_scan": SafetyTool(project_root, sandbox_manager),
"trufflehog_scan": TruffleHogTool(project_root, sandbox_manager),
"osv_scan": OSVScannerTool(project_root, sandbox_manager),
# 安全知识查询
"query_security_knowledge": SecurityKnowledgeQueryTool(),
"get_vulnerability_knowledge": GetVulnerabilityKnowledgeTool(),
}
# 🔥 注册 RAG 工具到 Analysis Agent
if retriever:
analysis_tools["rag_query"] = RAGQueryTool(retriever)
analysis_tools["security_search"] = SecurityCodeSearchTool(retriever)
analysis_tools["function_context"] = FunctionContextTool(retriever)
logger.info("✅ RAG 工具 (rag_query, security_search, function_context) 已注册到 Analysis Agent")
else:
logger.warning("⚠️ RAG 未初始化,rag_query/security_search/function_context 工具不可用")
# Verification 工具
# 🔥 导入沙箱工具
from app.services.agent.tools import (
SandboxTool, SandboxHttpTool, VulnerabilityVerifyTool,
# 多语言代码测试工具
PhpTestTool, PythonTestTool, JavaScriptTestTool, JavaTestTool,
GoTestTool, RubyTestTool, ShellTestTool, UniversalCodeTestTool,
# 漏洞验证专用工具
CommandInjectionTestTool, SqlInjectionTestTool, XssTestTool,
PathTraversalTestTool, SstiTestTool, DeserializationTestTool,
UniversalVulnTestTool,
# 🔥 新增:通用代码执行工具 (LLM 驱动的 Fuzzing Harness)
RunCodeTool, ExtractFunctionTool,
)
verification_tools = {