Compare commits

...

5 Commits

83 changed files with 2425 additions and 205 deletions

1
.gitignore vendored
View File

@ -5,6 +5,7 @@ chat_uploads/
*.db-shm
*.db-wal
*.db-journal
*.instance.lock
*.sqlite
*.sqlite3

View File

@ -384,7 +384,7 @@ multi_agent:
enabled: true
robot_default_agent_mode: single # 企微/钉钉/飞书机器人默认:single | deep | plan_execute | supervisor
batch_use_multi_agent: false # true 时「批量任务」队列中每个子任务也走 Pi 多代理(成本更高)
# plan_execute 专用:execute↔replan 外层循环上限,0 表示 原生默认 10。主/子代理 ReAct 轮次见 agent.max_iterations。
# plan_execute 专用:向 executor 委派的外层步数预算上限;0 表示不单独限制(主/子代理 ReAct 轮次统一由 agent.max_iterations 控制)。
plan_execute_loop_max_iterations: 0
sub_agent_user_context_max_runes: 0 # 子代理 task 描述中注入用户原文;0=不截断(默认),>0=总字符上限,负数=禁用
without_general_sub_agent: false # false 时保留 Deep 内置 general-purpose 子代理

View File

@ -77,7 +77,7 @@ func FromRunResult(db *database.DB, result *multiagent.RunResult, in Input) Deci
}
d := Decide(db, in)
if result != nil {
if d.CompletionReason == multiagent.ReasonUnfinishedPlan {
if !d.Finalizable && len(result.UnfinishedPlanSteps) > 0 {
d.UnfinishedPlanSteps = result.UnfinishedPlanSteps
}
result.Finalized = d.Finalized
@ -127,7 +127,9 @@ func Decide(db *database.DB, in Input) Decision {
if d.CompletionReason == ReasonVerified {
d.CompletionReason = status
}
if d.CompletionReason == multiagent.ReasonUnfinishedPlan && isEmptyCandidate(text) {
if (d.CompletionReason == multiagent.ReasonUnfinishedPlan ||
d.CompletionReason == multiagent.ReasonIterationLimit ||
d.CompletionReason == multiagent.ReasonPlanningIterationLimit) && isEmptyCandidate(text) {
d.FinalText = ""
d.CandidateResponseLen = 0
}

View File

@ -36,11 +36,12 @@ type FrontMatter struct {
// OrchestratorMarkdown 从 agents 目录解析出的主代理(Deep 协调者)定义。
type OrchestratorMarkdown struct {
Filename string
AgentName string // 写入 deep.Config.Name / 流式事件过滤
DisplayName string
Description string
Instruction string
Filename string
AgentName string // 写入 deep.Config.Name / 流式事件过滤
DisplayName string
Description string
Instruction string
MaxIterations int
}
// MarkdownDirLoad 一次扫描 agents 目录的结果(子代理不含主代理文件)。
@ -243,11 +244,12 @@ func orchestratorFromParsed(filename string, fm FrontMatter, body string) (*Orch
}
agentID := sanitizeAgentAgentID(rawID)
return &OrchestratorMarkdown{
Filename: filepath.Base(strings.TrimSpace(filename)),
AgentName: agentID,
DisplayName: display,
Description: strings.TrimSpace(fm.Description),
Instruction: strings.TrimSpace(body),
Filename: filepath.Base(strings.TrimSpace(filename)),
AgentName: agentID,
DisplayName: display,
Description: strings.TrimSpace(fm.Description),
Instruction: strings.TrimSpace(body),
MaxIterations: fm.MaxIterations,
}, nil
}
@ -256,11 +258,12 @@ func orchestratorConfigFromOrchestrator(o *OrchestratorMarkdown) config.MultiAge
return config.MultiAgentSubConfig{}
}
return config.MultiAgentSubConfig{
ID: o.AgentName,
Name: o.DisplayName,
Description: o.Description,
Instruction: o.Instruction,
Kind: "orchestrator",
ID: o.AgentName,
Name: o.DisplayName,
Description: o.Description,
Instruction: o.Instruction,
MaxIterations: o.MaxIterations,
Kind: "orchestrator",
}
}

View File

@ -73,8 +73,8 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
t.Fatal(err)
}
}
write(OrchestratorMarkdownFilename, "---\nname: Deep\n---\n\ndeep\n")
write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\n---\n\npe\n")
write(OrchestratorMarkdownFilename, "---\nname: Deep\nmax_iterations: 400\n---\n\ndeep\n")
write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\nmax_iterations: 600\n---\n\npe\n")
write(OrchestratorSupervisorMarkdownFilename, "---\nname: SV\n---\n\nsv\n")
write("worker.md", "---\nid: worker\nname: Worker\n---\n\nw\n")
@ -82,10 +82,10 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" {
if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" || load.Orchestrator.MaxIterations != 400 {
t.Fatalf("deep: %+v", load.Orchestrator)
}
if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" {
if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" || load.OrchestratorPlanExecute.MaxIterations != 600 {
t.Fatalf("pe: %+v", load.OrchestratorPlanExecute)
}
if load.OrchestratorSupervisor == nil || load.OrchestratorSupervisor.Instruction != "sv" {

View File

@ -79,6 +79,7 @@ type App struct {
storageHandler *handler.StorageHandler // 运行空间占用统计与垃圾清理
auditSvc *audit.Service
pluginHub *pluginhub.Manager
instanceUnlock func()
}
// New 创建新应用
@ -104,16 +105,22 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
router.Use(corsMiddleware(cfg.Server.CORSAllowedOrigins))
router.Use(gzipMiddleware())
// 初始化数据库
// 初始化数据库前先申请排他实例锁,防止重复启动的新进程在端口绑定失败前提前执行
// HITL / MCP / 深度测评的重启恢复逻辑,篡改正在运行实例的活跃任务状态。
dbPath := cfg.Database.Path
if dbPath == "" {
dbPath = "data/conversations.db"
}
// 确保目录存在
if err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {
return nil, fmt.Errorf("创建数据库目录失败: %w", err)
instanceUnlock, err := lockDatabaseInstance(dbPath)
if err != nil {
return nil, err
}
keepInstanceLock := false
defer func() {
if !keepInstanceLock {
instanceUnlock()
}
}()
db, err := database.NewDB(dbPath, log.Logger)
if err != nil {
@ -155,9 +162,6 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
monitorRetention.PurgeExpired()
monitor.StartRetentionLoop(monitorRetention, log.Logger)
if err := handler.NewHITLManager(db, log.Logger).EnsureSchema(); err != nil {
log.Logger.Warn("初始化 HITL 表失败", zap.Error(err))
}
hitlRetention := hitl.NewService(db, cfg, log.Logger)
hitlRetention.PurgeExpired()
hitl.StartRetentionLoop(hitlRetention, log.Logger)
@ -559,6 +563,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
c2Handler: c2Handler,
storageHandler: storageHandler,
auditSvc: auditSvc,
instanceUnlock: instanceUnlock,
}
// 飞书/钉钉长连接(无需公网),启用时在后台启动;后续前端应用配置时会通过 RestartRobotConnections 重启
app.startRobotConnections()
@ -683,6 +688,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
)
agentHandler.StartDeepAssessmentRecovery()
keepInstanceLock = true
return app, nil
}
@ -911,6 +917,10 @@ func (a *App) shutdown() {
a.logger.Logger.Warn("关闭主数据库连接失败", zap.Error(err))
}
}
if a.instanceUnlock != nil {
a.instanceUnlock()
a.instanceUnlock = nil
}
}
// startRobotConnections 根据当前配置启动钉钉/飞书长连接(不先关闭已有连接,仅用于首次启动)

View File

@ -0,0 +1,38 @@
package app
import (
"fmt"
"os"
"path/filepath"
"sync"
)
// lockDatabaseInstance acquires a non-blocking OS kernel lock for dbPath before
// startup recovery mutates SQLite tables (such as hitl_interrupts, messages,
// mcp_executions, or deep_assessments). If a second server process is started
// accidentally while the primary server is still bound and running tasks, the
// second process fails fast without corrupting the live server's task state.
func lockDatabaseInstance(dbPath string) (func(), error) {
absPath, err := filepath.Abs(dbPath)
if err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
return nil, fmt.Errorf("创建数据库目录失败: %w", err)
}
lockPath := absPath + ".instance.lock"
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return nil, fmt.Errorf("打开实例锁文件失败 (%s): %w", lockPath, err)
}
if err := tryLockInstanceFile(f); err != nil {
_ = f.Close()
return nil, fmt.Errorf("另一个 CyberStrikeAI 服务实例正在运行并占用数据库 %s(请先停止旧进程,或在系统设置中使用一键更新)", dbPath)
}
var once sync.Once
return func() {
once.Do(func() {
_ = f.Close()
})
}, nil
}

View File

@ -0,0 +1,9 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !netbsd && !dragonfly && !windows
package app
import "os"
func tryLockInstanceFile(_ *os.File) error {
return nil
}

View File

@ -0,0 +1,28 @@
package app
import (
"path/filepath"
"strings"
"testing"
)
func TestLockDatabaseInstanceRejectsConcurrentOwnerAndReacquiresAfterUnlock(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "data", "conversations.db")
unlock, err := lockDatabaseInstance(dbPath)
if err != nil {
t.Fatalf("first lockDatabaseInstance failed: %v", err)
}
if _, err := lockDatabaseInstance(dbPath); err == nil || !strings.Contains(err.Error(), "另一个 CyberStrikeAI 服务实例正在运行") {
t.Fatalf("expected concurrent lock to be rejected with clear message, got: %v", err)
}
unlock()
unlock2, err := lockDatabaseInstance(dbPath)
if err != nil {
t.Fatalf("reacquiring lock after unlock failed: %v", err)
}
unlock2()
}

View File

@ -0,0 +1,13 @@
//go:build darwin || linux || freebsd || openbsd || netbsd || dragonfly
package app
import (
"os"
"golang.org/x/sys/unix"
)
func tryLockInstanceFile(f *os.File) error {
return unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
}

View File

@ -0,0 +1,13 @@
//go:build windows
package app
import (
"os"
"golang.org/x/sys/windows"
)
func tryLockInstanceFile(f *os.File) error {
return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{})
}

View File

@ -5,6 +5,7 @@ import (
"fmt"
"strings"
"cyberstrike-ai/internal/authctx"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/mcp"
@ -199,6 +200,15 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
if warn := project.SparseBodyWarningIfNeeded(f.Category, f.FactKey, f.Body); warn != "" {
msg += warn
}
if principal, hasPrincipal := authctx.PrincipalFromContext(ctx); !hasPrincipal || principal.HasPermission("asset:write") {
ownerID := ""
allowGlobal := true
if hasPrincipal {
ownerID = principal.UserID
allowGlobal = principal.ScopeFor("asset:write") == database.RBACScopeAll
}
_, _ = db.SyncFactTargetsToAssets(projectID, created, ownerID, allowGlobal)
}
return textResult(msg, false), nil
})

View File

@ -407,6 +407,11 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
if principal, ok := authctx.PrincipalFromContext(ctx); ok {
_ = db.SetResourceOwner("vulnerability", created.ID, principal.UserID)
_ = db.AssignResourceToUser(principal.UserID, "vulnerability", created.ID)
if projectID != "" && principal.HasPermission("asset:write") {
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, principal.UserID, principal.ScopeFor("asset:write") == database.RBACScopeAll)
}
} else if projectID != "" {
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, "", true)
}
db.NotifyVulnerabilityCreated(created)

View File

@ -130,7 +130,7 @@ type MultiAgentConfig struct {
Orchestration string `yaml:"orchestration,omitempty" json:"orchestration,omitempty"`
// MaxIteration 已废弃:统一使用 agent.max_iterations(YAML 中保留字段仅为兼容旧配置,运行时不读取)。
MaxIteration int `yaml:"max_iteration,omitempty" json:"max_iteration,omitempty"`
// PlanExecuteLoopMaxIterations plan_execute 模式下 execute↔replan 外层循环上限;0 表示用 Agent 默认 10。
// PlanExecuteLoopMaxIterations plan_execute 模式下向 executor 委派的外层步数上限;0 表示不单独限制(统一受 agent.max_iterations 约束)。
PlanExecuteLoopMaxIterations int `yaml:"plan_execute_loop_max_iterations,omitempty" json:"plan_execute_loop_max_iterations,omitempty"`
// SubAgentMaxIterations 已废弃:子代理与主代理均使用 agent.max_iterations(Markdown max_iterations>0 可覆盖)。
SubAgentMaxIterations int `yaml:"sub_agent_max_iterations,omitempty" json:"sub_agent_max_iterations,omitempty"`
@ -2358,7 +2358,7 @@ func Default() *Config {
},
OpenAI: OpenAIConfig{},
Agent: AgentConfig{
MaxIterations: 30, // 默认最大迭代次数
MaxIterations: 3000, // 默认最大迭代次数(与 multiagent.defaultAgentMaxIterations 一致)
ToolTimeoutMinutes: 10, // 单次工具执行默认最多 10 分钟,避免异常长时间占用
ToolWaitTimeoutSeconds: 60, // 外部 MCP 工具单轮最多等待 60 秒,超时后返回 execution_id 可继续等待
ExternalMCPMaxConcurrentPerServer: 2, // 单个外部 MCP server 默认最多 2 个工具同时执行

View File

@ -380,12 +380,16 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
result.Skipped++
continue
}
if existingProject.String != asset.ProjectID {
result.Skipped++
result.ProjectConflicts++
continue
existingProj := strings.TrimSpace(existingProject.String)
if existingProj != asset.ProjectID {
if existingProj != "" || asset.ProjectID == "" {
result.Skipped++
result.ProjectConflicts++
continue
}
}
_, err = tx.Exec(`UPDATE assets SET
project_id=CASE WHEN COALESCE(project_id, '')='' AND ?<>'' THEN ? ELSE project_id END,
host=CASE WHEN ?<>'' THEN ? ELSE host END, ip=CASE WHEN ?<>'' THEN ? ELSE ip END,
domain=CASE WHEN ?<>'' THEN ? ELSE domain END, protocol=CASE WHEN ?<>'' THEN ? ELSE protocol END,
title=CASE WHEN ?<>'' THEN ? ELSE title END, server=CASE WHEN ?<>'' THEN ? ELSE server END,
@ -399,6 +403,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
criticality=CASE WHEN ?<>'' THEN ? ELSE criticality END,
tags_json=CASE WHEN ?<>'[]' THEN ? ELSE tags_json END,
last_seen_at=?, updated_at=? WHERE id=?`,
asset.ProjectID, asset.ProjectID,
asset.Host, asset.Host, asset.IP, asset.IP, asset.Domain, asset.Domain, asset.Protocol, asset.Protocol,
asset.Title, asset.Title, asset.Server, asset.Server, asset.Country, asset.Country, asset.Province, asset.Province,
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery,

View File

@ -456,6 +456,12 @@ func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
return fmt.Errorf("设置对话项目失败: %w", err)
}
if oldProjectID != projectID {
if oldProjectID == "" && projectID != "" {
_, _ = tx.Exec(
`UPDATE assets SET project_id = ?, updated_at = ? WHERE last_scan_conversation_id = ? AND COALESCE(project_id, '') = ''`,
projectID, time.Now(), conversationID,
)
}
rows, err := tx.Query(`SELECT id FROM vulnerabilities WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, conversationID, oldProjectID)
if err != nil {
return fmt.Errorf("查询对话关联漏洞失败: %w", err)

View File

@ -0,0 +1,484 @@
package database
import (
"database/sql"
"encoding/json"
"errors"
"strings"
"time"
"cyberstrike-ai/internal/surfaceingest"
)
const (
maxProjectSyncFacts = 500
maxProjectSyncExecutions = 80
maxProjectSyncUserPrompts = 40
maxProjectSyncVulns = 500
maxProjectSyncChainNodes = 500
)
type projectScopeJSON struct {
Targets []string `json:"targets"`
Exclude []string `json:"exclude"`
}
func parseProjectScopeTargets(raw string) (targets, exclude string) {
var payload projectScopeJSON
if json.Unmarshal([]byte(strings.TrimSpace(raw)), &payload) != nil {
return "", ""
}
return strings.Join(payload.Targets, "\n"), strings.Join(payload.Exclude, "\n")
}
func isStructuredTargetFact(category, factKey string) bool {
cat := strings.ToLower(strings.TrimSpace(category))
key := strings.ToLower(strings.TrimSpace(factKey))
return cat == "target" || cat == "infra" ||
strings.HasPrefix(key, "target/") || strings.HasPrefix(key, "infra/")
}
func isArtifactOnlyFactKey(factKey string) bool {
key := strings.ToLower(strings.TrimSpace(factKey))
return strings.HasPrefix(key, "artifact/")
}
func extractAttackChainTargetMetadata(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" || !strings.HasPrefix(raw, "{") {
return ""
}
var meta map[string]any
if json.Unmarshal([]byte(raw), &meta) != nil {
return ""
}
var parts []string
for _, k := range []string{"target", "host", "url", "domain", "ip"} {
if v, ok := meta[k].(string); ok && strings.TrimSpace(v) != "" {
parts = append(parts, strings.TrimSpace(v))
}
}
return strings.Join(parts, "\n")
}
func unwrapStoredToolExecutionText(raw string) string {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return ""
}
if strings.HasPrefix(trimmed, "{") {
var envelope struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}
if json.Unmarshal([]byte(trimmed), &envelope) == nil && len(envelope.Content) > 0 {
var b strings.Builder
for _, item := range envelope.Content {
if item.Text != "" {
if b.Len() > 0 {
b.WriteByte('\n')
}
b.WriteString(item.Text)
}
}
return b.String()
}
}
return trimmed
}
func surfaceHitHost(hit surfaceingest.SurfaceHit) string {
if hit.Domain != "" {
return hit.Domain
}
return hit.IP
}
func clipSurfaceSource(value string, max int) string {
value = strings.TrimSpace(value)
runes := []rune(value)
if len(runes) <= max {
return value
}
return string(runes[:max])
}
func isEndpointValidationError(err error) bool {
if err == nil {
return false
}
text := err.Error()
return strings.Contains(text, "invalid HTTP method") || strings.Contains(text, "endpoint path")
}
// CountSharedProjectFacts counts non-deprecated project facts excluding automatic session checkpoints.
func (db *DB) CountSharedProjectFacts(projectID string) (int, error) {
projectID = strings.TrimSpace(projectID)
if db == nil || projectID == "" {
return 0, nil
}
var count int
err := db.QueryRow(
`SELECT COUNT(*) FROM project_facts WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'`,
projectID,
).Scan(&count)
return count, err
}
func (db *DB) applyProjectSurfaceHits(projectID, source, sourceQuery, ownerUserID string, allowGlobal bool, hits []surfaceingest.SurfaceHit) ([]string, error) {
projectID = strings.TrimSpace(projectID)
if db == nil || projectID == "" || len(hits) == 0 {
return nil, nil
}
scope := RBACScopeAssigned
if allowGlobal || strings.TrimSpace(ownerUserID) == "" {
scope = RBACScopeAll
}
access := RBACListAccess{UserID: ownerUserID, Scope: scope}
var applied []string
for _, hit := range hits {
asset := &Asset{
ProjectID: projectID,
Host: surfaceHitHost(hit),
IP: hit.IP,
Domain: hit.Domain,
Port: hit.Port,
Protocol: hit.Protocol,
Source: source,
SourceQuery: clipSurfaceSource(sourceQuery, 500),
Status: "active",
}
res, err := db.UpsertAssetsInProject([]*Asset{asset}, ownerUserID, allowGlobal, projectID)
if err != nil {
var invalid *AssetValidationError
if errors.As(err, &invalid) {
continue
}
return applied, err
}
if len(res.AppliedIDs) == 0 {
continue
}
id := res.AppliedIDs[0]
applied = append(applied, id)
for _, ep := range hit.Endpoints {
epErr := db.PutAssetEndpoint(&AssetEndpoint{AssetID: id, Method: ep.Method, Path: ep.Path}, access)
if epErr != nil && !isEndpointValidationError(epErr) {
return applied, epErr
}
}
}
return applied, nil
}
func (db *DB) projectSeedsAndExclusions(projectID string) ([]surfaceingest.ScopeSeed, []surfaceingest.ScopeSeed, string) {
var scopeTargets, scopeExclude string
if proj, err := db.GetProject(projectID); err == nil && proj != nil {
scopeTargets, scopeExclude = parseProjectScopeTargets(proj.ScopeJSON)
}
excluded := surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeExclude))
rows, err := db.ListAssetScopeSeeds(5000, AssetListFilter{ProjectID: projectID}, RBACListAccess{Scope: RBACScopeAll})
var seeds []surfaceingest.ScopeSeed
if err == nil {
for _, r := range rows {
seeds = append(seeds, surfaceingest.ScopeSeed{Host: r.Host, IP: r.IP, Domain: r.Domain})
}
}
if scopeTargets != "" {
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractDeclaredTargets(scopeTargets))...)
}
return seeds, excluded, scopeTargets
}
// SyncFactTargetsToAssets materializes targets referenced in a saved project fact into the project's asset library.
func (db *DB) SyncFactTargetsToAssets(projectID string, fact *ProjectFact, ownerUserID string, allowGlobal bool) ([]string, error) {
projectID = strings.TrimSpace(projectID)
if db == nil || projectID == "" || fact == nil || fact.Confidence == "deprecated" || IsContextCheckpointKey(fact.FactKey) || isArtifactOnlyFactKey(fact.FactKey) {
return nil, nil
}
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
return nil, nil
}
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
var structured, prose []string
if isStructuredTargetFact(fact.Category, fact.FactKey) {
structured = append(structured, fact.Summary, fact.Body)
} else {
structured = append(structured, fact.Summary)
prose = append(prose, fact.Body)
}
hits := surfaceingest.ExtractPrecipitatedTargets(structured, prose, seeds, excluded)
return db.applyProjectSurfaceHits(projectID, "project_fact", fact.FactKey, ownerUserID, allowGlobal, hits)
}
// SyncVulnerabilityTargetToAssets materializes a recorded vulnerability's target into the project's asset library.
func (db *DB) SyncVulnerabilityTargetToAssets(projectID, target, ownerUserID string, allowGlobal bool) ([]string, error) {
projectID = strings.TrimSpace(projectID)
target = strings.TrimSpace(target)
if db == nil || projectID == "" || target == "" {
return nil, nil
}
if proj, err := db.GetProject(projectID); err != nil || proj == nil || proj.Status == ProjectStatusArchived {
return nil, nil
}
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
hits := surfaceingest.ExtractPrecipitatedTargets([]string{target}, nil, seeds, excluded)
return db.applyProjectSurfaceHits(projectID, "vulnerability", target, ownerUserID, allowGlobal, hits)
}
// IngestBoundConversationSurface writes in-scope discoveries from classic chat or batch tool outputs
// into the bound project's shared asset library.
func (db *DB) IngestBoundConversationSurface(conversationID, toolName, content, ownerUserID string, allowGlobal bool) (int, error) {
conversationID = strings.TrimSpace(conversationID)
if db == nil || conversationID == "" || strings.TrimSpace(content) == "" {
return 0, nil
}
projectID, err := db.GetConversationProjectID(conversationID)
if err != nil || strings.TrimSpace(projectID) == "" {
return 0, nil
}
projectID = strings.TrimSpace(projectID)
proj, err := db.GetProject(projectID)
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
return 0, nil
}
if ownerUserID == "" {
_ = db.QueryRow(`SELECT COALESCE(owner_user_id, '') FROM conversations WHERE id = ?`, conversationID).Scan(&ownerUserID)
ownerUserID = strings.TrimSpace(ownerUserID)
}
seeds, excluded, _ := db.projectSeedsAndExclusions(projectID)
// Also seed from explicit targets declared in this conversation's user prompts or target facts.
promptRows, err := db.Query(
`SELECT content FROM messages WHERE conversation_id = ? AND role = 'user' ORDER BY created_at DESC LIMIT 10`,
conversationID,
)
if err == nil {
var userTexts []string
for promptRows.Next() {
var body string
if promptRows.Scan(&body) == nil && strings.TrimSpace(body) != "" {
userTexts = append(userTexts, body)
}
}
_ = promptRows.Close()
if len(userTexts) > 0 {
promptHits := surfaceingest.ExtractPrecipitatedTargets(userTexts, nil, seeds, excluded)
if len(promptHits) > 0 {
_, _ = db.applyProjectSurfaceHits(projectID, "chat", "conversation_prompt", ownerUserID, allowGlobal, promptHits)
seeds = append(seeds, surfaceingest.SeedsFromHits(promptHits)...)
}
}
}
factRows, err := db.Query(
`SELECT category, fact_key, summary, COALESCE(body, '') FROM project_facts
WHERE project_id = ? AND confidence != 'deprecated' AND fact_key NOT LIKE 'note/context-%'
ORDER BY updated_at DESC LIMIT 60`,
projectID,
)
if err == nil {
var structured []string
for factRows.Next() {
var cat, key, summary, body string
if factRows.Scan(&cat, &key, &summary, &body) == nil && !isArtifactOnlyFactKey(key) {
structured = append(structured, summary)
if isStructuredTargetFact(cat, key) {
structured = append(structured, body)
}
}
}
_ = factRows.Close()
if len(structured) > 0 {
seeds = append(seeds, surfaceingest.SeedsFromHits(surfaceingest.ExtractPrecipitatedTargets(structured, nil, nil, excluded))...)
}
}
if len(seeds) == 0 {
return 0, nil
}
hits, _ := surfaceingest.Ingest(content, seeds, excluded)
applied, err := db.applyProjectSurfaceHits(projectID, "chat", toolName, ownerUserID, allowGlobal, hits)
return len(applied), err
}
// SyncProjectPrecipitatedAssets backfills and synchronizes targets precipitated in classic
// conversations (project facts, promoted/cached attack-chain target nodes, vulnerabilities,
// scope_json targets, unassigned conversation-scanned assets, and in-scope tool outputs)
// into the project's shared asset library.
func (db *DB) SyncProjectPrecipitatedAssets(projectID, ownerUserID string, allowGlobal bool) (int, error) {
projectID = strings.TrimSpace(projectID)
if db == nil || projectID == "" {
return 0, nil
}
proj, err := db.GetProject(projectID)
if err != nil || proj == nil || proj.Status == ProjectStatusArchived {
return 0, nil
}
ownerUserID = strings.TrimSpace(ownerUserID)
adopted := 0
// 1. Adopt unassigned assets that were scanned in conversations bound to this project.
now := time.Now()
var adoptRes sql.Result
if allowGlobal || ownerUserID == "" {
adoptRes, _ = db.Exec(
`UPDATE assets SET project_id = ?, updated_at = ?
WHERE COALESCE(project_id, '') = '' AND COALESCE(last_scan_conversation_id, '') <> ''
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
projectID, now, projectID,
)
} else {
adoptRes, _ = db.Exec(
`UPDATE assets SET project_id = ?, updated_at = ?
WHERE COALESCE(project_id, '') = '' AND COALESCE(owner_user_id, '') = ?
AND COALESCE(last_scan_conversation_id, '') <> ''
AND EXISTS (SELECT 1 FROM conversations c WHERE c.id = assets.last_scan_conversation_id AND c.project_id = ?)`,
projectID, now, ownerUserID, projectID,
)
}
if adoptRes != nil {
if n, nErr := adoptRes.RowsAffected(); nErr == nil {
adopted += int(n)
}
}
seeds, excluded, scopeTargets := db.projectSeedsAndExclusions(projectID)
var structuredTexts []string
var proseTexts []string
if scopeTargets != "" {
structuredTexts = append(structuredTexts, scopeTargets)
}
// 2. Collect recorded vulnerabilities in this project.
vulnRows, err := db.Query(
`SELECT COALESCE(target, ''), COALESCE(targets_json, '') FROM vulnerabilities
WHERE project_id = ? AND manually_archived = 0 ORDER BY updated_at DESC LIMIT ?`,
projectID, maxProjectSyncVulns,
)
if err == nil {
for vulnRows.Next() {
var target, targetsJSON string
if vulnRows.Scan(&target, &targetsJSON) != nil {
continue
}
if strings.TrimSpace(target) != "" {
structuredTexts = append(structuredTexts, target)
}
if strings.TrimSpace(targetsJSON) != "" && targetsJSON != "[]" {
var list []string
if json.Unmarshal([]byte(targetsJSON), &list) == nil && len(list) > 0 {
structuredTexts = append(structuredTexts, strings.Join(list, "\n"))
}
}
}
_ = vulnRows.Close()
}
// 3. Collect target nodes from conversation attack chains bound to this project.
chainRows, err := db.Query(
`SELECT acn.node_name, COALESCE(acn.metadata, '')
FROM attack_chain_nodes acn
INNER JOIN conversations c ON c.id = acn.conversation_id
WHERE c.project_id = ? AND LOWER(acn.node_type) = 'target'
ORDER BY acn.created_at DESC LIMIT ?`,
projectID, maxProjectSyncChainNodes,
)
if err == nil {
for chainRows.Next() {
var name, metadata string
if chainRows.Scan(&name, &metadata) != nil {
continue
}
if strings.TrimSpace(name) != "" {
structuredTexts = append(structuredTexts, name)
}
if metaTargets := extractAttackChainTargetMetadata(metadata); metaTargets != "" {
structuredTexts = append(structuredTexts, metaTargets)
}
}
_ = chainRows.Close()
}
// 4. Collect project blackboard facts.
factRows, err := db.Query(
`SELECT category, fact_key, summary, COALESCE(body, '')
FROM project_facts
WHERE project_id = ? AND confidence != 'deprecated'
ORDER BY pinned DESC, updated_at DESC LIMIT ?`,
projectID, maxProjectSyncFacts,
)
if err == nil {
for factRows.Next() {
var cat, key, summary, body string
if factRows.Scan(&cat, &key, &summary, &body) != nil {
continue
}
if IsContextCheckpointKey(key) {
if strings.TrimSpace(body) != "" {
proseTexts = append(proseTexts, body)
}
continue
}
if isArtifactOnlyFactKey(key) {
continue
}
if isStructuredTargetFact(cat, key) {
structuredTexts = append(structuredTexts, summary, body)
} else {
structuredTexts = append(structuredTexts, summary)
if strings.TrimSpace(body) != "" {
proseTexts = append(proseTexts, body)
}
}
}
_ = factRows.Close()
}
// 5. Collect user prompts and completed tool outputs from bound non-assessment conversations.
promptRows, err := db.Query(
`SELECT m.content
FROM messages m
INNER JOIN conversations c ON c.id = m.conversation_id
WHERE c.project_id = ? AND m.role = 'user'
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
ORDER BY m.created_at DESC LIMIT ?`,
projectID, maxProjectSyncUserPrompts,
)
if err == nil {
for promptRows.Next() {
var content string
if promptRows.Scan(&content) == nil && strings.TrimSpace(content) != "" {
structuredTexts = append(structuredTexts, content)
}
}
_ = promptRows.Close()
}
execRows, err := db.Query(
`SELECT COALESCE(te.result, '')
FROM tool_executions te
INNER JOIN conversations c ON c.id = te.conversation_id
WHERE c.project_id = ? AND te.status = 'completed' AND COALESCE(te.result, '') <> ''
AND NOT EXISTS (SELECT 1 FROM deep_assessment_sessions das WHERE das.conversation_id = c.id)
ORDER BY te.created_at DESC LIMIT ?`,
projectID, maxProjectSyncExecutions,
)
if err == nil {
for execRows.Next() {
var raw string
if execRows.Scan(&raw) == nil {
if text := unwrapStoredToolExecutionText(raw); text != "" {
proseTexts = append(proseTexts, text)
}
}
}
_ = execRows.Close()
}
hits := surfaceingest.ExtractPrecipitatedTargets(structuredTexts, proseTexts, seeds, excluded)
applied, err := db.applyProjectSurfaceHits(projectID, "project_sync", "project_precipitation", ownerUserID, allowGlobal, hits)
if err != nil {
return adopted + len(applied), err
}
return adopted + len(applied), nil
}

View File

@ -248,6 +248,27 @@ func (h *AssetHandler) List(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
syncRequested := strings.TrimSpace(c.Query("sync_project_scope")) == "1" && filter.ProjectID != ""
syncedAssets := 0
projectFactCount := 0
if syncRequested {
if session, ok := security.CurrentSession(c); ok {
if security.SessionHasPermission(c, "project:read") &&
h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", filter.ProjectID) {
if security.SessionHasPermission(c, "asset:write") {
syncedAssets, _ = h.db.SyncProjectPrecipitatedAssets(
filter.ProjectID,
session.UserID,
session.ScopeFor("asset:write") == database.RBACScopeAll,
)
}
projectFactCount, _ = h.db.CountSharedProjectFacts(filter.ProjectID)
}
} else {
syncedAssets, _ = h.db.SyncProjectPrecipitatedAssets(filter.ProjectID, "", true)
projectFactCount, _ = h.db.CountSharedProjectFacts(filter.ProjectID)
}
}
assets, total, err := h.db.ListAssets(pageSize, (page-1)*pageSize, filter, assetAccess(c))
if err != nil {
h.logger.Error("加载资产失败", zap.Error(err))
@ -258,7 +279,12 @@ func (h *AssetHandler) List(c *gin.Context) {
if totalPages < 1 {
totalPages = 1
}
c.JSON(http.StatusOK, gin.H{"assets": assets, "total": total, "page": page, "page_size": pageSize, "total_pages": totalPages})
resp := gin.H{"assets": assets, "total": total, "page": page, "page_size": pageSize, "total_pages": totalPages}
if syncRequested {
resp["synced_assets"] = syncedAssets
resp["project_fact_count"] = projectFactCount
}
c.JSON(http.StatusOK, resp)
}
func assetListFilterFromQuery(c *gin.Context) (database.AssetListFilter, error) {

View File

@ -150,6 +150,15 @@ func (h *ConversationHandler) SetConversationProject(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if projectID != "" {
if session, ok := security.CurrentSession(c); ok {
if security.SessionHasPermission(c, "asset:write") {
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
}
} else {
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, "", true)
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "projectId": projectID})
}

View File

@ -60,6 +60,9 @@ func (h *AgentHandler) syncAssessmentAssets(actor assessmentAssetActor, t *deepa
}
var ids []string
if strings.TrimSpace(t.ProjectID) != "" {
if strings.TrimSpace(t.CollectionID) == "" && actor.can("asset:write") {
_, _ = h.db.SyncProjectPrecipitatedAssets(t.ProjectID, actor.userID, actor.scope("asset:write") == database.RBACScopeAll)
}
scoped, err := h.assessmentScopeIDs(actor, t)
if err != nil {
return err
@ -155,29 +158,54 @@ func (h *AgentHandler) assessmentSurfaceSeeds(actor assessmentAssetActor, t *dee
return seeds, nil
}
// IngestMCPSurface is the execution-service entry for a successful MCP result.
// It claims the execution ID before writing. Deep assessment AfterTool uses the
// same claim, so one receipt is parsed once. Conversations that are not a
// single assessment task are left unclaimed for a later chat or batch writer.
// Local tool output never reaches this hook and is still ingested by AfterTool,
// which also keeps the asset-library Signal wake.
// IngestMCPSurface is the execution-service entry for a successful MCP or local
// tool result. It claims the execution ID before writing so each receipt is
// parsed at most once across MCP hooks and Deep Assessment AfterTool.
func (h *AgentHandler) IngestMCPSurface(ctx context.Context, tool, executionID, content string) {
if h == nil || h.db == nil || h.deepAssessments == nil || h.deepAssessmentRuntime == nil {
if h == nil || h.db == nil {
return
}
taskID, ok, err := h.db.AssessmentIDForConversation(mcp.MCPConversationIDFromContext(ctx))
if err != nil || !ok {
convID := strings.TrimSpace(mcp.MCPConversationIDFromContext(ctx))
if convID == "" {
return
}
task, err := h.deepAssessments.Store.Get(taskID)
if err != nil || task == nil {
if h.deepAssessments != nil && h.deepAssessmentRuntime != nil {
taskID, ok, err := h.db.AssessmentIDForConversation(convID)
if err == nil && ok {
task, getErr := h.deepAssessments.Store.Get(taskID)
if getErr != nil || task == nil {
return
}
if !surfaceingest.Claim(executionID) {
return
}
if ingestErr := h.deepAssessmentRuntime.ingestToolSurface(task, tool, agentruntime.ToolResult{Content: content, ExecutionID: executionID}); ingestErr != nil && h.logger != nil {
h.logger.Warn("自动写入资产库失败", zap.String("task", task.ID), zap.String("tool", tool), zap.Error(ingestErr))
}
return
}
}
if tool == "create_asset" || tool == "update_asset" || tool == "delete_asset" || tool == "query_assets" || tool == "get_asset" {
return
}
ownerID := ""
allowGlobal := true
if principal, hasPrincipal := authctx.PrincipalFromContext(ctx); hasPrincipal {
if !principal.HasPermission("asset:write") {
return
}
ownerID = principal.UserID
allowGlobal = principal.ScopeFor("asset:write") == database.RBACScopeAll
}
projectID, err := h.db.GetConversationProjectID(convID)
if err != nil || strings.TrimSpace(projectID) == "" {
return
}
if !surfaceingest.Claim(executionID) {
return
}
if err = h.deepAssessmentRuntime.ingestToolSurface(task, tool, agentruntime.ToolResult{Content: content, ExecutionID: executionID}); err != nil && h.logger != nil {
h.logger.Warn("自动写入资产库失败", zap.String("task", task.ID), zap.String("tool", tool), zap.Error(err))
if _, err := h.db.IngestBoundConversationSurface(convID, tool, content, ownerID, allowGlobal); err != nil && h.logger != nil {
h.logger.Warn("对话工具输出写入项目资产库失败", zap.String("conversation", convID), zap.String("tool", tool), zap.Error(err))
}
}

View File

@ -195,6 +195,7 @@ func TestDeepAssessmentUnassociatedProjectExtractsDeclaredTargetsAndNormalizesAs
func assessmentAssetRouter(h *AgentHandler, user string) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
assetHandler := NewAssetHandler(h.db, h.logger)
router.Use(func(c *gin.Context) {
c.Set(security.ContextSessionKey, security.Session{
UserID: user,
@ -206,10 +207,104 @@ func assessmentAssetRouter(h *AgentHandler, user string) *gin.Engine {
})
})
router.Use(security.RBACMiddleware(h.db))
router.GET("/api/assets", assetHandler.List)
router.POST("/api/deep-assessments", h.CreateDeepAssessment)
return router
}
func TestClassicChatPrecipitatedAssetsSyncIntoProjectScopeAndAssessment(t *testing.T) {
h, task := deepAssessmentFixture(t)
project, err := h.db.CreateProject(&database.Project{Name: "货讯通科技"})
if err != nil {
t.Fatal(err)
}
// 1. Simulate an unassigned asset created before the conversation was bound to the project.
unassigned := &database.Asset{Host: "https://portal.hxt-example.com"}
if _, err = h.db.UpsertAssets([]*database.Asset{unassigned}, task.OwnerID, true); err != nil {
t.Fatal(err)
}
// 2. Simulate classic chat conversation bound to the project with target facts, attack-chain nodes, vulns, and tool output.
conv, err := h.db.CreateConversation("货讯通渗透", database.ConversationCreateMeta{ProjectID: project.ID})
if err != nil {
t.Fatal(err)
}
_ = h.db.SetResourceOwner("conversation", conv.ID, task.OwnerID)
if _, err = h.db.UpsertProjectFact(&database.ProjectFact{
ProjectID: project.ID,
FactKey: "target/primary",
Category: "target",
Summary: "主域 hxt-example.com,发现 portal.hxt-example.com 与 api.hxt-example.com:8443",
Body: "使用 exploit.py 读取 config.json,参考 https://github.com/projectdiscovery/httpx",
Confidence: "tentative",
SourceConversationID: conv.ID,
}); err != nil {
t.Fatal(err)
}
if err = h.db.SaveAttackChainNode(conv.ID, "node_1", "target", "edi.hxt-example.com", "", `{"target":"https://edi.hxt-example.com/ws"}`, 0); err != nil {
t.Fatal(err)
}
if _, err = h.db.CreateVulnerability(&database.Vulnerability{
ConversationID: conv.ID,
ProjectID: project.ID,
Title: "订单接口越权",
Severity: "high",
Target: "https://tms.hxt-example.com/api/orders",
}); err != nil {
t.Fatal(err)
}
// 3. Selecting the project in CreateDrawer queries GET /api/assets?project_id=...&sync_project_scope=1.
router := assessmentAssetRouter(h, task.OwnerID)
req := httptest.NewRequest("GET", "/api/assets?project_id="+project.ID+"&page=1&page_size=6&sync_project_scope=1", nil)
resp := httptest.NewRecorder()
router.ServeHTTP(resp, req)
if resp.Code != http.StatusOK {
t.Fatalf("sync_project_scope status=%d body=%s", resp.Code, resp.Body.String())
}
var listed struct {
Assets []*database.Asset `json:"assets"`
Total int `json:"total"`
}
if err = json.Unmarshal(resp.Body.Bytes(), &listed); err != nil {
t.Fatal(err)
}
if listed.Total < 5 {
t.Fatalf("expected >=5 synced project assets, got total=%d assets=%+v", listed.Total, listed.Assets)
}
for _, want := range []string{"hxt-example.com", "portal.hxt-example.com", "api.hxt-example.com", "edi.hxt-example.com", "tms.hxt-example.com"} {
if !assetInProject(t, h.db, project.ID, want) {
t.Fatalf("expected classic chat target %s in project asset library", want)
}
}
for _, noise := range []string{"exploit.py", "config.json", "github.com"} {
if assetInProject(t, h.db, project.ID, noise) {
t.Fatalf("noise host %s leaked into project asset library", noise)
}
}
// 4. Creating the deep assessment automatically links all synced project assets.
createBody := `{"name":"货讯通深度测评","objective":"全面评估认证与越权风险","project_id":"` + project.ID + `"}`
createReq := httptest.NewRequest("POST", "/api/deep-assessments", strings.NewReader(createBody))
createReq.Header.Set("Content-Type", "application/json")
createResp := httptest.NewRecorder()
router.ServeHTTP(createResp, createReq)
if createResp.Code != http.StatusCreated {
t.Fatalf("create deep assessment failed: %d %s", createResp.Code, createResp.Body.String())
}
var created struct {
Task deepassessment.Task `json:"task"`
}
if err = json.Unmarshal(createResp.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
linked := linkedAssetNames(t, h.db, created.Task.ID)
for _, want := range []string{"portal.hxt-example.com", "api.hxt-example.com", "edi.hxt-example.com", "tms.hxt-example.com"} {
if !linked[want] {
t.Fatalf("expected %s linked to deep assessment, got %v", want, linked)
}
}
}
func linkedAssetNames(t *testing.T, db *database.DB, taskID string) map[string]bool {
t.Helper()
rows, err := db.Query(`SELECT COALESCE(domain,''), COALESCE(ip,''), COALESCE(host,'') FROM assets JOIN deep_assessment_assets a ON a.asset_id=assets.id WHERE a.task_id=?`, taskID)

View File

@ -156,18 +156,21 @@ func finalizationCheckMessage(d agentfinalizer.Decision) string {
if d.Finalizable {
return "已交付本轮回复。"
}
if d.CompletionReason == multiagent.ReasonUnfinishedPlan {
switch d.CompletionReason {
case multiagent.ReasonUnfinishedPlan:
return unfinishedPlanNotice(d.UnfinishedPlanSteps)
case multiagent.ReasonIterationLimit, multiagent.ReasonPlanningIterationLimit:
return iterationLimitNotice(d.CompletionReason, d.UnfinishedPlanSteps)
default:
return finalizationBlockedMessage(d)
}
return finalizationBlockedMessage(d)
}
func unfinishedPlanNotice(steps []multiagent.PlanStep) string {
func formatPlanStepBullets(steps []multiagent.PlanStep) string {
if len(steps) == 0 {
return "本轮任务未完成,计划中仍有待执行或进行中的步骤。"
return ""
}
var notice strings.Builder
fmt.Fprintf(&notice, "本轮任务未完成,还有 %d 个计划步骤未结束。\n", len(steps))
var b strings.Builder
escapeTitle := strings.NewReplacer(
"\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~",
"[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "&", "\\&",
@ -181,9 +184,27 @@ func unfinishedPlanNotice(steps []multiagent.PlanStep) string {
if title == "" {
title = "步骤 #" + step.ID
}
fmt.Fprintf(&notice, "\n- %s · %s", status, escapeTitle.Replace(title))
fmt.Fprintf(&b, "\n- %s · %s", status, escapeTitle.Replace(title))
}
return notice.String()
return b.String()
}
func unfinishedPlanNotice(steps []multiagent.PlanStep) string {
if len(steps) == 0 {
return "本轮任务未完成,计划中仍有待执行或进行中的步骤。"
}
return fmt.Sprintf("本轮任务未完成,还有 %d 个计划步骤未结束。\n%s", len(steps), formatPlanStepBullets(steps))
}
func iterationLimitNotice(reason string, steps []multiagent.PlanStep) string {
base := "本轮代理已达到最大迭代轮次上限,任务尚未完成。可发送「继续」基于已有轨迹接着执行,或在配置中调大 agent.max_iterations。"
if reason == multiagent.ReasonPlanningIterationLimit {
base = "Plan-Execute 已达到计划执行步数预算上限,任务尚未完成。可发送「继续」基于已有轨迹接着执行,或在配置中调大 multi_agent.plan_execute_loop_max_iterations(设为 0 表示不单独限制)。"
}
if len(steps) == 0 {
return base
}
return fmt.Sprintf("%s\n\n未结束的计划步骤(%d 项):\n%s", base, len(steps), formatPlanStepBullets(steps))
}
func finalizationBlockedMessage(d agentfinalizer.Decision) string {
@ -197,6 +218,13 @@ func finalizationBlockedMessage(d agentfinalizer.Decision) string {
}
return notice
}
if d.CompletionReason == multiagent.ReasonIterationLimit || d.CompletionReason == multiagent.ReasonPlanningIterationLimit {
notice := iterationLimitNotice(d.CompletionReason, d.UnfinishedPlanSteps)
if text := strings.TrimSpace(d.FinalText); text != "" {
return notice + "\n\n**本轮已生成的内容(阶段性结果)**\n\n" + text
}
return notice
}
notice, keepText := finalizationBlockNotice(d)
parts := make([]string, 0, 4)
if keepText {

View File

@ -85,3 +85,33 @@ func TestUnfinishedPlanWithoutDraftShowsOnlyNotice(t *testing.T) {
}
}
}
func TestIterationLimitPreservesDraftAndUnfinishedStepsWithoutRawBlockedCheck(t *testing.T) {
for _, reason := range []string{multiagent.ReasonIterationLimit, multiagent.ReasonPlanningIterationLimit} {
result := &multiagent.RunResult{
Response: "已确认入口服务开放 8080 端口。",
RuntimeStatus: agentfinalizer.StatusBlocked,
RuntimeCompletionReason: reason,
UnfinishedPlanSteps: []multiagent.PlanStep{
{ID: "2", Subject: "验证后台弱口令", Status: "in_progress"},
},
}
decision := agentfinalizer.FromRunResult(nil, result, agentfinalizer.Input{})
if decision.Finalizable || decision.Status != agentfinalizer.StatusBlocked || decision.CompletionReason != reason {
t.Fatalf("unexpected decision for %s: %+v", reason, decision)
}
reply := finalizationBlockedMessage(decision)
for _, want := range []string{"继续", "进行中 · 验证后台弱口令", "阶段性结果", "已确认入口服务开放 8080 端口。"} {
if !strings.Contains(reply, want) {
t.Fatalf("reason=%s reply missing %q: %q", reason, want, reply)
}
}
if strings.Contains(reply, "agent run status is blocked") {
t.Fatalf("reason=%s reply leaked raw internal check: %q", reason, reply)
}
checkMsg := finalizationCheckMessage(decision)
if strings.Contains(checkMsg, "已确认入口服务开放 8080 端口。") || !strings.Contains(checkMsg, "验证后台弱口令") {
t.Fatalf("reason=%s expected concise check message, got %q", reason, checkMsg)
}
}
}

View File

@ -570,8 +570,13 @@ func (m *HITLManager) waitDecision(ctx context.Context, p *pendingInterrupt, tim
defer timer.Stop()
timeoutCh = timer.C
}
select {
case d := <-p.decideCh:
var dbPollCh <-chan time.Time
if m.db != nil && p.InterruptID != "" {
dbPoll := time.NewTicker(2 * time.Second)
defer dbPoll.Stop()
dbPollCh = dbPoll.C
}
applyDecision := func(d hitlDecision) (hitlDecision, error) {
// 只有 review_edit 模式允许改参;其他模式一律忽略 edited arguments
if p.Mode != "review_edit" && len(d.EditedArguments) > 0 {
d.EditedArguments = nil
@ -579,15 +584,51 @@ func (m *HITLManager) waitDecision(ctx context.Context, p *pendingInterrupt, tim
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET status='decided', decision=?, decision_comment=?, decided_at=?, decided_by='human' WHERE id=?`,
d.Decision, d.Comment, time.Now(), p.InterruptID)
return d, nil
case <-timeoutCh:
comment := "HITL timeout auto-reject for safety"
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET status='timeout', decision='reject', decision_comment=?, decided_at=?, decided_by='system' WHERE id=?`,
comment, time.Now(), p.InterruptID)
return hitlDecision{Decision: "reject", Comment: comment}, nil
case <-ctx.Done():
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET status='cancelled', decision='reject', decision_comment='task cancelled', decided_at=?, decided_by='system' WHERE id=?`,
time.Now(), p.InterruptID)
return hitlDecision{Decision: "reject", Comment: "task cancelled"}, ctx.Err()
}
for {
select {
case d := <-p.decideCh:
return applyDecision(d)
case <-dbPollCh:
select {
case d := <-p.decideCh:
return applyDecision(d)
default:
}
var status, decision, comment string
err := m.db.QueryRow(`SELECT status, COALESCE(decision,''), COALESCE(decision_comment,'') FROM hitl_interrupts WHERE id=?`, p.InterruptID).
Scan(&status, &decision, &comment)
if errors.Is(err, sql.ErrNoRows) {
return hitlDecision{Decision: "reject", Comment: "interrupt removed"}, context.Canceled
}
status = strings.ToLower(strings.TrimSpace(status))
if err != nil || status == "pending" {
continue
}
switch status {
case "decided":
if strings.EqualFold(strings.TrimSpace(decision), "approve") {
return hitlDecision{Decision: "approve", Comment: comment}, nil
}
return hitlDecision{Decision: "reject", Comment: comment}, nil
case "timeout":
return hitlDecision{Decision: "reject", Comment: comment}, nil
default:
if strings.EqualFold(strings.TrimSpace(comment), "dismissed by user") {
return hitlDecision{Decision: "reject", Comment: comment}, nil
}
return hitlDecision{Decision: "reject", Comment: comment}, context.Canceled
}
case <-timeoutCh:
comment := "HITL timeout auto-reject for safety"
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET status='timeout', decision='reject', decision_comment=?, decided_at=?, decided_by='system' WHERE id=?`,
comment, time.Now(), p.InterruptID)
return hitlDecision{Decision: "reject", Comment: comment}, nil
case <-ctx.Done():
_, _ = m.db.Exec(`UPDATE hitl_interrupts SET status='cancelled', decision='reject', decision_comment='task cancelled', decided_at=?, decided_by='system' WHERE id=?`,
time.Now(), p.InterruptID)
return hitlDecision{Decision: "reject", Comment: "task cancelled"}, ctx.Err()
}
}
}

View File

@ -1,10 +1,13 @@
package handler
import (
"context"
"database/sql"
"errors"
"path/filepath"
"strings"
"testing"
"time"
"cyberstrike-ai/internal/database"
@ -249,3 +252,29 @@ func TestAuditAgentInterruptIsNotHumanPendingWork(t *testing.T) {
t.Fatalf("unexpected human pending result: %#v", items)
}
}
func TestWaitDecisionExitsWhenInterruptCancelledInDB(t *testing.T) {
db, err := database.NewDB(filepath.Join(t.TempDir(), "hitl-wait-cancel.db"), zap.NewNop())
if err != nil {
t.Fatalf("open db: %v", err)
}
defer func() { _ = db.Close() }()
manager := NewHITLManager(db, zap.NewNop())
if err := manager.EnsureSchema(); err != nil {
t.Fatalf("ensure schema: %v", err)
}
p, err := manager.CreatePendingInterrupt("conv-1", "msg-1", "approval", "exec", "call-1", `{}`, "human")
if err != nil {
t.Fatalf("create interrupt: %v", err)
}
if _, err := db.Exec(`UPDATE hitl_interrupts SET status='cancelled', decision='reject', decision_comment='process restarted' WHERE id=?`, p.InterruptID); err != nil {
t.Fatalf("cancel interrupt in db: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, waitErr := manager.waitDecision(ctx, p, 10*time.Minute)
if !errors.Is(waitErr, context.Canceled) {
t.Fatalf("expected waitDecision to return context.Canceled on external DB cancellation, got %v", waitErr)
}
}

View File

@ -721,5 +721,8 @@ func (h *ProjectHandler) PromoteAttackChain(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if security.SessionHasPermission(c, "asset:write") {
_, _ = h.db.SyncProjectPrecipitatedAssets(projectID, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
}
c.JSON(http.StatusOK, result)
}

View File

@ -104,6 +104,23 @@ func (s *ExecutionService) SetSurfaceIngest(fn SurfaceIngestFunc) {
s.mu.Unlock()
}
// IngestCompletedSurface dispatches completed tool text (including local host tools)
// to the registered surface ingest callback when present.
func (s *ExecutionService) IngestCompletedSurface(ctx context.Context, toolName, executionID, plainText string) {
if s == nil {
return
}
s.mu.Lock()
ingest := s.surfaceIngest
s.mu.Unlock()
if ingest == nil {
return
}
if text := strings.TrimSpace(plainText); text != "" {
ingest(ctx, toolName, executionID, text)
}
}
func NewExecutionService(storage MonitorStorage, logger *zap.Logger) *ExecutionService {
if logger == nil {
logger = zap.NewNop()

View File

@ -1150,6 +1150,10 @@ func (s *Server) FinishToolExecution(ctx context.Context, executionID, toolName
}
}
if !failed && s.executionService != nil && strings.TrimSpace(resultText) != "" {
s.executionService.IngestCompletedSurface(ctx, exec.ToolName, id, resultText)
}
s.updateStats(exec.ToolName, exec.Status)
if s.storage != nil {

View File

@ -820,12 +820,159 @@ func TestPiReportsIncompleteModelStreamRetries(t *testing.T) {
}
func TestPiTransportFailureClassifiesTLSHandshakeReset(t *testing.T) {
err := fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established (ECONNRESET)")
err := fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established (ECONNRESET) [endpoint=api.openai.com, route=direct]")
fields := ClientRunErrorFields(err)
if fields["errorKind"] != "model_transient" || fields["reasonCode"] != "model_tls_reset" {
t.Fatalf("unexpected error fields: %+v", fields)
}
if msg := ClientRunErrorMessage(err); !strings.Contains(msg, "TLS") {
t.Fatalf("expected localized TLS error message, got %q", msg)
msg := ClientRunErrorMessage(err)
if !strings.Contains(msg, "TLS") || !strings.Contains(msg, "api.openai.com") || !strings.Contains(msg, "直连未走代理") {
t.Fatalf("expected localized TLS error message with endpoint and route hint, got %q", msg)
}
proxied := ClientRunErrorMessage(fmt.Errorf("Pi runtime error: Connection error.: Client network socket disconnected before secure TLS connection was established [endpoint=api.example.com:8443, route=proxy http://127.0.0.1:7890]"))
if !strings.Contains(proxied, "api.example.com:8443") || !strings.Contains(proxied, "http://127.0.0.1:7890") {
t.Fatalf("expected proxied route hint, got %q", proxied)
}
}
func TestPiPlanExecuteUsesAgentMaxIterationsBeyondLegacy33TurnsAnd10Steps(t *testing.T) {
cfg := piTestConfig(t)
cfg.Agent.MaxIterations = 80
cfg.MultiAgent.PlanExecuteLoopMaxIterations = 0 // default 0 must not cap at 10 steps or 33 turns
const totalSteps = 12
var mainTurns atomic.Int32
var execCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Tools []struct {
Function struct {
Name string `json:"name"`
} `json:"function"`
} `json:"tools"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
return
}
isMain := false
for _, tool := range body.Tools {
if tool.Function.Name == "exit" {
isMain = true
break
}
}
if !isMain {
n := execCalls.Add(1)
piReply(w, "", "", nil, fmt.Sprintf("step-%d-evidence", n))
return
}
// 12 steps * 3 main turns (in_progress -> task -> completed) + exit = 37 main turns (> 33) and 12 executor delegations (> 10).
turn := int(mainTurns.Add(1))
stepIdx := (turn - 1) / 3
phase := (turn - 1) % 3
if stepIdx < totalSteps {
todos := make([]map[string]any, 0, totalSteps)
for i := 0; i < totalSteps; i++ {
status := "pending"
if i < stepIdx {
status = "completed"
} else if i == stepIdx {
if phase == 2 {
status = "completed"
} else {
status = "in_progress"
}
}
todos = append(todos, map[string]any{
"content": fmt.Sprintf("Step %d", i+1),
"status": status,
})
}
switch phase {
case 0, 2:
piReply(w, "write_todos", fmt.Sprintf("todos-%d", turn), map[string]any{"todos": todos}, "")
case 1:
piReply(w, "task", fmt.Sprintf("task-%d", stepIdx+1), map[string]any{
"subagent_type": "executor",
"description": fmt.Sprintf("Run step %d", stepIdx+1),
}, "")
}
return
}
piReply(w, "exit", "finish", map[string]any{"final_result": "All 12 plan-execute steps verified."}, "")
}))
defer server.Close()
cfg.OpenAI.BaseURL = server.URL + "/v1"
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, mcp.NewServer(zap.NewNop()), nil, zap.NewNop(), 80)
res, err := RunMultiAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "plan-execute-long", "", "Execute full 12-step plan.", nil, nil, nil, "", "plan_execute", nil, "")
if err != nil {
t.Fatal(err)
}
if res.RuntimeStatus != "completed" || res.Response != "All 12 plan-execute steps verified." {
t.Fatalf("expected completed 12-step plan_execute run, got %+v (mainTurns=%d execCalls=%d)", res, mainTurns.Load(), execCalls.Load())
}
if execCalls.Load() != totalSteps || mainTurns.Load() <= 33 {
t.Fatalf("unexpected call counts: mainTurns=%d execCalls=%d", mainTurns.Load(), execCalls.Load())
}
}
func TestPiPlanExecuteExplicitStepBudgetAllowsSummaryAndKeepsBlockedReason(t *testing.T) {
cfg := piTestConfig(t)
cfg.Agent.MaxIterations = 20
cfg.MultiAgent.PlanExecuteLoopMaxIterations = 1
var mainTurns atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Tools []struct {
Function struct {
Name string `json:"name"`
} `json:"function"`
} `json:"tools"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
isMain := false
for _, tool := range body.Tools {
if tool.Function.Name == "exit" {
isMain = true
break
}
}
if !isMain {
piReply(w, "", "", nil, "step-1-ok")
return
}
switch mainTurns.Add(1) {
case 1:
piReply(w, "write_todos", "plan-1", map[string]any{"todos": []map[string]any{
{"content": "Step 1", "status": "completed"},
{"content": "Step 2", "status": "in_progress"},
}}, "")
case 2:
piReply(w, "task", "task-1", map[string]any{"subagent_type": "executor", "description": "Run step 1"}, "")
case 3:
piReply(w, "task", "task-2", map[string]any{"subagent_type": "executor", "description": "Run step 2"}, "")
default:
piReply(w, "exit", "exit-partial", map[string]any{"final_result": "Completed step 1; step 2 awaits more budget."}, "")
}
}))
defer server.Close()
cfg.OpenAI.BaseURL = server.URL + "/v1"
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, mcp.NewServer(zap.NewNop()), nil, zap.NewNop(), 20)
res, err := RunMultiAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "plan-execute-budget", "", "Run two steps.", nil, nil, nil, "", "plan_execute", nil, "")
if err != nil {
t.Fatal(err)
}
if res.RuntimeStatus != "blocked" || res.RuntimeCompletionReason != ReasonPlanningIterationLimit {
t.Fatalf("expected blocked planning_iteration_limit, got %+v", res)
}
if res.Response != "Completed step 1; step 2 awaits more budget." {
t.Fatalf("expected summary response to be preserved, got %q", res.Response)
}
if len(res.UnfinishedPlanSteps) != 1 || res.UnfinishedPlanSteps[0].Subject != "Step 2" {
t.Fatalf("expected unfinished step 2 to be retained, got %+v", res.UnfinishedPlanSteps)
}
}

View File

@ -122,13 +122,17 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
registry[id] = sub
catalog = append(catalog, id+": "+sub.Description)
}
instruction, _ := resolveMainOrchestratorInstruction(mode, ma, loaded)
instruction, meta := resolveMainOrchestratorInstruction(mode, ma, loaded)
prompt := project.AppendSystemPromptBlock(instruction, extra)
prompt += "\n\nAvailable specialists:\n" + strings.Join(catalog, "\n") + "\nUse task to delegate a concrete objective. Each child receives only the tools permitted for it and this conversation. Verify evidence before reporting completion."
if mode == "plan_execute" {
prompt += "\nCreate a concrete plan using the available task-board tools or a concise plan in text. Delegate one step at a time to executor using task, examine the result, update the plan, and replan when evidence requires it. Finish with the verified deliverable."
}
main := &piRun{cfg: cfg, ag: ag, db: db, projectID: projectID, conversationID: conversationID, agentID: "main", systemPrompt: prompt, systemPromptPrefix: instruction, history: history, roleTools: roleTools, progress: progress, reasoning: intent, sessionKey: mode}
var orchestratorMaxIterations int
if meta != nil {
orchestratorMaxIterations = meta.MaxIterations
}
main := &piRun{cfg: cfg, ag: ag, db: db, projectID: projectID, conversationID: conversationID, agentID: "main", systemPrompt: prompt, systemPromptPrefix: instruction, history: history, roleTools: roleTools, progress: progress, reasoning: intent, sessionKey: mode, maxTurns: resolveMaxIterations(cfg, orchestratorMaxIterations)}
str := map[string]any{"type": "string"}
main.extraTools = []agentruntime.Tool{
{Name: "task", Description: "Delegate a concrete task to a named specialist and return its evidence-backed result", Parameters: piToolSchema(map[string]any{"subagent_type": str, "description": str}, "subagent_type", "description")},
@ -142,16 +146,8 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
}
planLimitReached := false
planCalls := 0
// plan_execute_loop_max_iterations <= 0 表示不单独限制 executor 委派步数,统一受 agent.max_iterations(及主代理 max_iterations)约束。
planLimit := ma.PlanExecuteLoopMaxIterations
if planLimit <= 0 {
planLimit = 10
}
if mode == "plan_execute" {
main.maxTurns = planLimit*3 + 3
if cap := agentMaxIterations(cfg); cap < main.maxTurns {
main.maxTurns = cap
}
}
main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "exit", Description: "Finish with the verified final deliverable", Parameters: piToolSchema(map[string]any{"final_result": str}, "final_result")})
if mode == "supervisor" {
main.extraTools = append(main.extraTools, agentruntime.Tool{Name: "transfer_to_agent", Description: "Delegate to a named specialist", Parameters: piToolSchema(map[string]any{"agent_name": str, "description": str}, "agent_name", "description")})
@ -178,16 +174,6 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
return agentruntime.ToolResult{Content: string(b)}, nil
}
id, _ := call.Arguments["subagent_type"].(string)
if mode == "plan_execute" {
idsMu.Lock()
if planCalls >= planLimit {
planLimitReached = true
idsMu.Unlock()
return agentruntime.ToolResult{Content: "Planning step budget reached. Existing results are preserved; further execution needs a new budget.", Terminate: true}, nil
}
planCalls++
idsMu.Unlock()
}
if call.Name == "transfer_to_agent" {
id, _ = call.Arguments["agent_name"].(string)
}
@ -196,6 +182,19 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
if !ok || strings.TrimSpace(task) == "" {
return agentruntime.ToolResult{}, fmt.Errorf("unknown specialist or empty task")
}
if mode == "plan_execute" && planLimit > 0 {
idsMu.Lock()
if planCalls >= planLimit {
planLimitReached = true
idsMu.Unlock()
return agentruntime.ToolResult{
Content: fmt.Sprintf("Planning step budget (%d) reached. Stop delegating further task steps and summarize verified findings and remaining plan items via exit.", planLimit),
IsError: true,
}, nil
}
planCalls++
idsMu.Unlock()
}
tools := sub.RoleTools
if sub.BindRole != "" {
role, ok := cfg.Roles[sub.BindRole]
@ -217,14 +216,23 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo
idsMu.Lock()
childIDs = append(childIDs, res.MCPExecutionIDs...)
idsMu.Unlock()
return agentruntime.ToolResult{Content: res.Response, IsError: err != nil}, err
content := res.Response
if res.Status == ReasonIterationLimit {
note := "[Sub-agent reached its max_iterations limit before finishing this step; inspect recorded tool results/facts and split remaining work if needed.]"
if strings.TrimSpace(content) == "" {
content = note
} else {
content += "\n\n" + note
}
}
return agentruntime.ToolResult{Content: content, IsError: err != nil}, err
}
res, err := main.run(ctx, message)
if res != nil {
idsMu.Lock()
if planLimitReached {
res.RuntimeStatus = "blocked"
res.RuntimeCompletionReason = "planning_iteration_limit"
res.RuntimeCompletionReason = ReasonPlanningIterationLimit
}
if deliverable != "" {
res.Response = deliverable
@ -719,7 +727,8 @@ func piResultFromRuntime(res *agentruntime.Result, ids []string, plan piRunPlan)
out.RuntimeCompletionReason = ReasonModelOutputTruncated
case "iteration_limit":
out.RuntimeStatus = "blocked"
out.RuntimeCompletionReason = "iteration_limit"
out.RuntimeCompletionReason = ReasonIterationLimit
out.UnfinishedPlanSteps = plan.unfinishedSteps()
case "canceled":
out.RuntimeStatus = "cancelled"
case "failed":

View File

@ -4,7 +4,9 @@ import (
"context"
"cyberstrike-ai/internal/config"
"errors"
"fmt"
"math/rand/v2"
"regexp"
"strings"
"time"
)
@ -12,6 +14,29 @@ import (
const defaultRunRetryMaxBackoff = 30 * time.Second
const modelOutputRecoveryKey = "_cyberstrike_model_output_recovery"
var modelRouteTagPattern = regexp.MustCompile(`(?i)\[endpoint=([^,\]]+),\s*route=([^\]]+)\]`)
func formatModelEndpointHint(raw string) string {
m := modelRouteTagPattern.FindStringSubmatch(raw)
if len(m) != 3 {
return ""
}
endpoint := strings.TrimSpace(m[1])
route := strings.TrimSpace(m[2])
if endpoint == "" {
return ""
}
lowerRoute := strings.ToLower(route)
switch {
case lowerRoute == "direct":
return fmt.Sprintf("(%s,当前直连未走代理)", endpoint)
case strings.HasPrefix(lowerRoute, "proxy "):
return fmt.Sprintf("(%s,经代理 %s)", endpoint, strings.TrimSpace(route[len("proxy "):]))
default:
return fmt.Sprintf("(%s)", endpoint)
}
}
func transientRetryBackoff(attempt int, maxBackoff time.Duration) time.Duration {
if attempt < 0 {
attempt = 0
@ -42,26 +67,27 @@ func ClientRunErrorMessage(err error) string {
func piModelTransportFailure(raw string) (code, detail string) {
text := strings.ToLower(raw)
hint := formatModelEndpointHint(raw)
switch {
case strings.Contains(text, "und_err_headers_timeout"):
return "model_headers_timeout", "等待模型服务响应头超时"
return "model_headers_timeout", "等待模型服务" + hint + "响应头超时"
case strings.Contains(text, "und_err_body_timeout"):
return "model_stream_timeout", "模型响应流长时间未收到新数据"
return "model_stream_timeout", "模型" + hint + "响应流长时间未收到新数据"
case strings.Contains(text, "stream ended without finish_reason"):
return "model_stream_incomplete", "模型响应流提前关闭,未收到结束标记"
return "model_stream_incomplete", "模型" + hint + "响应流提前关闭,未收到结束标记"
case strings.Contains(text, "before secure tls connection was established") || strings.Contains(text, "tls handshake"):
return "model_tls_reset", "与模型服务的 TLS 握手中断,连接被重置"
return "model_tls_reset", "与模型服务" + hint + "的 TLS 握手中断,连接被重置"
case strings.Contains(text, "und_err_connect_timeout") || strings.Contains(text, "connecttimeouterror") || strings.Contains(text, "etimedout"):
return "model_connect_timeout", "连接模型服务超时"
return "model_connect_timeout", "连接模型服务" + hint + "超时"
case strings.Contains(text, "econnrefused") || strings.Contains(text, "connection refused"):
return "model_connection_refused", "模型服务拒绝连接"
return "model_connection_refused", "模型服务" + hint + "拒绝连接"
case strings.Contains(text, "eai_again") || strings.Contains(text, "getaddrinfo"):
return "model_dns_failure", "模型服务域名解析暂时失败"
return "model_dns_failure", "模型服务" + hint + "域名解析暂时失败"
case strings.Contains(text, "econnreset") || strings.Contains(text, "econnaborted") ||
strings.Contains(text, "connection reset") || strings.Contains(text, "socket disconnected") ||
strings.Contains(text, "socket hang up") || strings.Contains(text, "other side closed") ||
strings.Contains(text, "und_err_socket") || strings.Contains(text, "connection error"):
return "model_connection_reset", "与模型服务的网络连接中断"
return "model_connection_reset", "与模型服务" + hint + "的网络连接中断"
default:
return "", ""
}

View File

@ -1,8 +1,10 @@
package multiagent
const (
ReasonModelOutputTruncated = "model_output_truncated"
ReasonUnfinishedPlan = "unfinished_plan"
ReasonModelOutputTruncated = "model_output_truncated"
ReasonUnfinishedPlan = "unfinished_plan"
ReasonIterationLimit = "iteration_limit"
ReasonPlanningIterationLimit = "planning_iteration_limit"
)
type PlanStep struct {

View File

@ -201,7 +201,7 @@ func BuildAssetLibraryBlock(db *database.DB, projectID string, access database.R
b.WriteString("该项目目前没有可读资产。新发现的目标用 create_asset 写入这个项目。\n")
return b.String(), nil
}
fmt.Fprintf(&b, "当前可读资产 %d 个。下面最多列出 12 个,其余用 query_assets 按该项目分页读取。\n", total)
fmt.Fprintf(&b, "当前可读资产 %d 个。下面最多列出 12 个,其余用 query_assets 按该项目分页读取;新发现的目标用 create_asset 写入这个项目。\n", total)
for _, asset := range assets {
fmt.Fprintf(&b, "- %s\n", assetLibraryLine(asset))
}

View File

@ -0,0 +1,304 @@
package surfaceingest
import (
"net"
"net/url"
"strings"
"golang.org/x/net/publicsuffix"
)
// nonTargetReferenceDomains lists external documentation, package registry,
// scanner, and OOB callback domains commonly cited in security notes or POCs
// that must never be auto-materialized as customer project assets.
var nonTargetReferenceDomains = []string{
"github.com",
"githubusercontent.com",
"gitlab.com",
"owasp.org",
"mitre.org",
"nist.gov",
"cve.org",
"portswigger.net",
"hacktricks.xyz",
"w3.org",
"xmlsoap.org",
"mozilla.org",
"googleapis.com",
"gstatic.com",
"jsdelivr.net",
"unpkg.com",
"npmjs.org",
"pypi.org",
"golang.org",
"python.org",
"dnslog.cn",
"ceye.io",
"oastify.com",
"oast.pro",
"oast.fun",
"oast.live",
"oast.me",
"oast.online",
"burpcollaborator.net",
"interact.sh",
"shodan.io",
"fofa.info",
"qianxin.com",
"360.net",
}
// ambiguousTwoLabelExtensions lists file extensions that collide with ICANN
// 2-letter/new TLDs when written bare in prose without scheme or port
// (for example "exploit.py", "run.sh", "README.md", "spac.do", "backup.zip").
var ambiguousTwoLabelExtensions = map[string]bool{
"py": true,
"sh": true,
"md": true,
"rs": true,
"pl": true,
"cc": true,
"so": true,
"do": true,
"zip": true,
"mov": true,
}
var allowedInternalSuffixes = map[string]bool{
"test": true,
"local": true,
"internal": true,
"lan": true,
"corp": true,
"example": true,
}
var publicResolverIPs = map[string]bool{
"8.8.8.8": true,
"8.8.4.4": true,
"1.1.1.1": true,
"1.0.0.1": true,
"114.114.114.114": true,
"223.5.5.5": true,
}
// IsNoiseTarget reports whether a candidate IP or domain is loopback,
// link-local/metadata, public DNS, or a known third-party reference/OOB host.
func IsNoiseTarget(ip, domain string) bool {
if ip != "" {
parsed := net.ParseIP(strings.TrimSpace(ip))
if parsed == nil ||
parsed.IsLoopback() ||
parsed.IsUnspecified() ||
parsed.IsLinkLocalUnicast() ||
parsed.IsLinkLocalMulticast() ||
parsed.IsMulticast() {
return true
}
if v4 := parsed.To4(); v4 != nil {
if v4[0] == 0 || v4[0] == 127 || v4[0] == 255 || (v4[0] == 169 && v4[1] == 254) {
return true
}
// Subnet masks such as 255.255.255.0
if v4[0] >= 224 {
return true
}
}
if publicResolverIPs[parsed.String()] {
return true
}
}
if domain != "" {
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
if lower == "" || lower == "localhost" || strings.HasSuffix(lower, ".localhost") || strings.HasSuffix(lower, ".invalid") {
return true
}
for _, ref := range nonTargetReferenceDomains {
if lower == ref || strings.HasSuffix(lower, "."+ref) {
return true
}
}
}
return false
}
func validBarePrecipitatedDomain(domain string) bool {
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
if lower == "" || IsNoiseTarget("", lower) || !validSurfaceDomain(lower) {
return false
}
labels := strings.Split(lower, ".")
last := labels[len(labels)-1]
if len(labels) == 2 && ambiguousTwoLabelExtensions[last] {
return false
}
_, icann := publicsuffix.PublicSuffix(lower)
if icann {
return true
}
return allowedInternalSuffixes[last]
}
// extractExplicitServiceTokens extracts only explicit http(s) URLs and host:port
// pairs from free-form prose (ignoring bare domain-like words unless seeded).
func extractExplicitServiceTokens(text string) []SurfaceHit {
if len(text) > surfaceTextLimit {
text = text[:surfaceTextLimit]
}
text = strings.ReplaceAll(text, "\r\n", "\n")
builder := &surfaceBuilder{scope: newSurfaceScope(nil, true), hits: map[string]*SurfaceHit{}}
lines := strings.Split(text, "\n")
if len(lines) > surfaceLineLimit {
lines = lines[:surfaceLineLimit]
}
for _, line := range lines {
if len(line) > 4000 {
line = line[:4000]
}
method := surfaceLineMethod(line)
urls := surfaceURLPattern.FindAllString(line, 20)
for _, raw := range urls {
raw = strings.TrimRight(raw, ".,;:")
parsed, err := url.Parse(raw)
if err != nil || parsed.Hostname() == "" {
continue
}
parsed.User = nil
scheme := strings.ToLower(parsed.Scheme)
if scheme != "http" && scheme != "https" {
continue
}
ip, domain, ok := classifySurfaceHost(parsed.Hostname())
if !ok || IsNoiseTarget(ip, domain) {
continue
}
if domain != "" && !validExplicitHostDomain(domain) {
continue
}
hit := builder.add(ip, domain, scheme, surfacePort(parsed))
if path := cleanSurfacePath(parsed.EscapedPath()); path != "" && path != "/" {
builder.addEndpoint(hit, method, path)
}
}
stripped := surfaceURLPattern.ReplaceAllString(line, " ")
for _, match := range surfaceHostPattern.FindAllStringSubmatch(stripped, 20) {
ip, domain, ok := classifySurfaceHost(match[1])
if !ok || IsNoiseTarget(ip, domain) {
continue
}
if domain != "" && !validExplicitHostDomain(domain) {
continue
}
port := atoiPort(match[2])
if port <= 0 || port > 65535 {
continue
}
protocol := ""
if port == 443 {
protocol = "https"
} else if port == 80 {
protocol = "http"
}
builder.add(ip, domain, protocol, port)
}
}
return builder.finish()
}
func validExplicitHostDomain(domain string) bool {
lower := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
if lower == "" || IsNoiseTarget("", lower) || !validSurfaceDomain(lower) {
return false
}
labels := strings.Split(lower, ".")
last := labels[len(labels)-1]
_, icann := publicsuffix.PublicSuffix(lower)
return icann || allowedInternalSuffixes[last]
}
func filterStructuredHits(hits []SurfaceHit) []SurfaceHit {
out := make([]SurfaceHit, 0, len(hits))
for _, hit := range hits {
if IsNoiseTarget(hit.IP, hit.Domain) {
continue
}
if hit.Domain != "" {
if hit.Port > 0 || hit.Protocol != "" || len(hit.Endpoints) > 0 {
if !validExplicitHostDomain(hit.Domain) {
continue
}
} else if !validBarePrecipitatedDomain(hit.Domain) {
continue
}
}
out = append(out, hit)
}
return out
}
// ExtractPrecipitatedTargets extracts project targets from structured target
// records (scope_json targets, target/infra facts, attack-chain target nodes,
// vulnerability targets, fact summaries) and then expands in-scope subdomains
// and endpoints across prose bodies and tool outputs without adopting unrelated
// external hosts or filename tokens.
func ExtractPrecipitatedTargets(structuredTexts, proseTexts []string, seeds, excluded []ScopeSeed) []SurfaceHit {
merged := map[string]*SurfaceHit{}
mergeHits := func(items []SurfaceHit) {
for _, item := range items {
if IsNoiseTarget(item.IP, item.Domain) {
continue
}
key := item.key()
if existing := merged[key]; existing != nil {
for _, ep := range item.Endpoints {
appendSurfaceEndpoint(existing, ep)
}
continue
}
copyHit := item
if len(item.Endpoints) > 0 {
copyHit.Endpoints = append([]SurfaceEndpoint(nil), item.Endpoints...)
}
merged[key] = &copyHit
}
}
for _, text := range structuredTexts {
if strings.TrimSpace(text) == "" {
continue
}
mergeHits(filterStructuredHits(ExtractDeclaredTargets(text)))
}
for _, text := range proseTexts {
if strings.TrimSpace(text) == "" {
continue
}
mergeHits(extractExplicitServiceTokens(text))
}
allSeeds := make([]ScopeSeed, 0, len(seeds)+len(merged))
allSeeds = append(allSeeds, seeds...)
for _, hit := range merged {
allSeeds = append(allSeeds, ScopeSeed{IP: hit.IP, Domain: hit.Domain})
}
if len(allSeeds) > 0 {
for _, text := range proseTexts {
if strings.TrimSpace(text) == "" {
continue
}
inScope, _ := ExtractSurface(text, allSeeds)
mergeHits(inScope)
}
}
// Re-run builder.finish()-style specificity collapsing: if host:443 exists,
// fold bare host:0 into host:443 so we don't create duplicate port=0 rows.
collapsed := &surfaceBuilder{scope: newSurfaceScope(nil, true), hits: map[string]*SurfaceHit{}}
for _, hit := range merged {
added := collapsed.add(hit.IP, hit.Domain, hit.Protocol, hit.Port)
for _, ep := range hit.Endpoints {
collapsed.addEndpoint(added, ep.Method, ep.Path)
}
}
return WithoutExcluded(collapsed.finish(), excluded)
}

View File

@ -0,0 +1,56 @@
package surfaceingest
import "testing"
func TestExtractPrecipitatedTargetsFiltersNoiseAndKeepsProjectAssets(t *testing.T) {
structured := []string{
"主域名 cargosmart.com,发现子域 portal.cargosmart.com、https://api.cargosmart.com:8443/v1/auth 和后台 203.0.113.25:8080",
"脚本 exploit.py 读取 config.json、web.xml、login.jsp、spac.do,本地 127.0.0.1:4444,参考 https://github.com/projectdiscovery/httpx 与 xxx.dnslog.cn",
}
prose := []string{
"subfinder 结果:edi.cargosmart.com\nhttps://owasp.org/www-project-top-ten/\nhttp://169.254.169.254/latest/meta-data/\nhttps://admin.hxt.com.cn/console\n无关裸词 other-company.org",
}
excluded := []ScopeSeed{{Domain: "skip.cargosmart.com"}}
hits := ExtractPrecipitatedTargets(structured, prose, nil, excluded)
got := map[string]bool{}
for _, hit := range hits {
if hit.Domain != "" {
got[hit.Domain] = true
}
if hit.IP != "" {
got[hit.IP] = true
}
}
for _, want := range []string{
"cargosmart.com",
"portal.cargosmart.com",
"api.cargosmart.com",
"edi.cargosmart.com",
"admin.hxt.com.cn",
"203.0.113.25",
} {
if !got[want] {
t.Fatalf("missing expected precipitated target %s in %+v", want, hits)
}
}
for _, unwanted := range []string{
"exploit.py",
"config.json",
"web.xml",
"login.jsp",
"spac.do",
"127.0.0.1",
"169.254.169.254",
"github.com",
"xxx.dnslog.cn",
"owasp.org",
"other-company.org",
} {
if got[unwanted] {
t.Fatalf("noise token %s leaked into precipitated targets: %+v", unwanted, hits)
}
}
}

View File

@ -1,18 +1,337 @@
import { execFileSync } from "node:child_process";
import { lookup as defaultDnsLookup } from "node:dns";
import { Resolver } from "node:dns/promises";
import { EventEmitter } from "node:events";
import { isIP } from "node:net";
import { Client, EnvHttpProxyAgent, Pool, install, setGlobalDispatcher, type Dispatcher } from "undici";
// Model credentials may use arbitrary custom header names. Fetch's default
// redirect handling only protects selected standard headers, so the isolated
// worker follows redirects explicitly and only within the original origin.
const redirects = new Set([301, 302, 303, 307, 308]);
const PRE_TLS_RETRY_DELAYS_MS = [200, 600];
const PRE_TLS_RETRY_DELAYS_MS = [150, 350, 600];
const AUTO_SELECT_FAMILY_TIMEOUT_MS = 2_000;
const CONNECT_TIMEOUT_MS = 20_000;
const DEFAULT_PUBLIC_DNS_SERVERS = ["223.5.5.5", "119.29.29.29", "1.1.1.1"];
// OpenSSL 3.5+/4.x sends a >1.6KB post-quantum (X25519MLKEM768) TLS 1.3 ClientHello
// that fragments across TCP segments and triggers deterministic ECONNRESET on many
// middleboxes, SNI routers, SLBs, and proxy tunnels. Classic ECDH curves keep the
// ClientHello ~386B in a single TCP segment.
const CLASSIC_ECDH_CURVES = "X25519:prime256v1:secp384r1";
interface ProxySettings {
httpProxy?: string;
httpsProxy?: string;
noProxy?: string;
source: "env" | "os" | "none";
}
interface TransportProfile {
id: "default" | "ipv4-h2" | "ipv4-tls12" | "direct-clean-dns" | "os-proxy";
allowH2: boolean;
ipv4Only: boolean;
tls12Compat: boolean;
disableSessionReuse: boolean;
useOsProxy?: boolean;
useCleanPublicDns?: boolean;
}
const BASE_PROFILES: readonly TransportProfile[] = [
{ id: "default", allowH2: false, ipv4Only: false, tls12Compat: false, disableSessionReuse: false },
{ id: "ipv4-h2", allowH2: true, ipv4Only: true, tls12Compat: false, disableSessionReuse: true },
{ id: "ipv4-tls12", allowH2: false, ipv4Only: true, tls12Compat: true, disableSessionReuse: true },
];
const DIRECT_CLEAN_DNS_PROFILE: TransportProfile = {
id: "direct-clean-dns",
allowH2: false,
ipv4Only: true,
tls12Compat: false,
disableSessionReuse: true,
useCleanPublicDns: true,
};
const DIRECT_PROXY_SETTINGS: ProxySettings = {
noProxy: "*",
source: "none",
};
const OS_PROXY_PROFILE: TransportProfile = {
id: "os-proxy",
allowH2: false,
ipv4Only: false,
tls12Compat: false,
disableSessionReuse: true,
useOsProxy: true,
};
const dispatcherCache = new Map<string, Dispatcher>();
const preferredProfileByOrigin = new Map<string, TransportProfile["id"]>();
const cleanDnsCache = new Map<string, { expiresAt: number; addresses: string[] }>();
let cachedOsProxy: { expiresAt: number; value: ProxySettings | undefined } | undefined;
function blocked(message: string): Response {
return new Response(JSON.stringify({ error: { type: "invalid_request_error", message: "Local model transport: " + message } }),
{ status: 400, headers: { "Content-Type": "application/json" } });
}
export function normalizeProxyUrl(raw: string | undefined, defaultScheme = "http"): string | undefined {
const trimmed = raw?.trim();
if (!trimmed) return undefined;
let candidate = trimmed;
if (/^socks5h:\/\//i.test(candidate)) {
candidate = "socks5://" + candidate.slice("socks5h://".length);
} else if (/^socks4a?:\/\//i.test(candidate)) {
candidate = "socks://" + candidate.replace(/^socks4a?:\/\//i, "");
} else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(candidate)) {
candidate = `${defaultScheme}://${candidate}`;
}
if (!URL.canParse(candidate)) return undefined;
const parsed = new URL(candidate);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:" && parsed.protocol !== "socks5:" && parsed.protocol !== "socks:") {
return undefined;
}
return candidate;
}
export function resolveEnvProxySettings(env: NodeJS.ProcessEnv = process.env): ProxySettings {
const allProxy = normalizeProxyUrl(env.all_proxy ?? env.ALL_PROXY);
const httpProxy = normalizeProxyUrl(env.http_proxy ?? env.HTTP_PROXY) ?? allProxy;
const httpsProxy = normalizeProxyUrl(env.https_proxy ?? env.HTTPS_PROXY) ?? httpProxy ?? allProxy;
const noProxy = env.no_proxy ?? env.NO_PROXY;
return {
httpProxy,
httpsProxy,
noProxy,
source: httpProxy || httpsProxy ? "env" : "none",
};
}
export function isLoopbackOrPrivateHost(rawHostname: string): boolean {
const host = rawHostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase();
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
return true;
}
const family = isIP(host);
if (family === 4) {
const parts = host.split(".").map(Number);
if (parts[0] === 127 || parts[0] === 10 || parts[0] === 0) return true;
if (parts[0] === 169 && parts[1] === 254) return true;
if (parts[0] === 192 && parts[1] === 168) return true;
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
return false;
}
if (family === 6) {
return host === "::1" || host === "::" || host.startsWith("fc") || host.startsWith("fd") || host.startsWith("fe80:");
}
return false;
}
// RFC 2544 benchmark range (198.18.0.0/15) and ULA (fc00::/7) are used as TUN Fake-IPs
// by Clash, Mihomo, Surge, and sing-box. When those tools are turned off, stale Fake-IP
// entries cached in OS or VMware NAT DNS fail with ECONNRESET until real DNS is queried.
export function isFakeIpAddress(rawAddress: string): boolean {
const addr = rawAddress.replace(/^\[(.+)\]$/, "$1").toLowerCase();
const family = isIP(addr);
if (family === 4) {
const parts = addr.split(".").map(Number);
return parts[0] === 198 && (parts[1] === 18 || parts[1] === 19);
}
if (family === 6) {
return addr.startsWith("fc") || addr.startsWith("fd");
}
return false;
}
const DOMESTIC_MODEL_HOST_SUFFIXES = [
".cn",
".deepseek.com",
".aliyuncs.com",
".volces.com",
".baidubce.com",
".tencentcloudapi.com",
".myqcloud.com",
".minimaxi.com",
".minimax.chat",
".stepfun.com",
".lingyiwanwu.com",
".xf-yun.com",
];
const DOMESTIC_MODEL_EXACT_HOSTS = new Set([
"api.deepseek.com",
"dashscope.aliyuncs.com",
"api.lkeap.cloud.tencent.com",
"api.minimaxi.com",
"api.minimax.chat",
"api.stepfun.com",
"api.lingyiwanwu.com",
"spark-api-open.xf-yun.com",
]);
export function isDomesticModelHost(rawHostname: string): boolean {
const host = rawHostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase();
if (!host || isIP(host) !== 0 || isLoopbackOrPrivateHost(host)) return false;
if (DOMESTIC_MODEL_EXACT_HOSTS.has(host)) return true;
return DOMESTIC_MODEL_HOST_SUFFIXES.some(suffix => host.endsWith(suffix));
}
export function isLocalClientProxy(proxy: ProxySettings): boolean {
const urls = [proxy.httpProxy, proxy.httpsProxy].filter((v): v is string => Boolean(v));
if (urls.length === 0) return false;
return urls.every(raw => {
if (!URL.canParse(raw)) return false;
return isLoopbackOrPrivateHost(new URL(raw).hostname);
});
}
async function resolveCleanPublicIpv4(hostname: string): Promise<string[]> {
const now = Date.now();
const cached = cleanDnsCache.get(hostname);
if (cached && now < cached.expiresAt) return cached.addresses;
const customServers = process.env.CYBERSTRIKE_CLEAN_DNS_SERVERS
?.split(/[,\s]+/)
.map(s => s.trim())
.filter(Boolean);
const resolver = new Resolver();
resolver.setServers(customServers?.length ? customServers : DEFAULT_PUBLIC_DNS_SERVERS);
let timer: NodeJS.Timeout | undefined;
try {
const resolved = await Promise.race([
resolver.resolve4(hostname),
new Promise<never>((_, reject) => {
timer = setTimeout(() => {
resolver.cancel();
reject(new Error("Clean DNS resolution timed out"));
}, 2_500);
}),
]);
const valid = resolved.filter(ip => isIP(ip) === 4 && !isFakeIpAddress(ip));
if (valid.length > 0) {
cleanDnsCache.set(hostname, { expiresAt: now + 60_000, addresses: valid });
return valid;
}
} catch {
// Fall back to system DNS lookup below if UDP 53 to public resolvers is blocked.
} finally {
if (timer) clearTimeout(timer);
}
return [];
}
function cleanPublicDnsLookup(
hostname: string,
options: { all?: boolean },
callback: (err: NodeJS.ErrnoException | null, address: string | { address: string; family: number }[], family?: number) => void,
): void {
if (isIP(hostname) !== 0 || isLoopbackOrPrivateHost(hostname)) {
defaultDnsLookup(hostname, options as any, callback as any);
return;
}
void resolveCleanPublicIpv4(hostname).then(addresses => {
if (addresses.length > 0) {
if (options?.all) {
callback(null, addresses.map(address => ({ address, family: 4 })));
} else {
callback(null, addresses[0], 4);
}
return;
}
defaultDnsLookup(hostname, options as any, callback as any);
});
}
export function parseDarwinScutilProxy(output: string): ProxySettings | undefined {
const field = (name: string): string | undefined => {
const match = output.match(new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, "m"));
return match?.[1]?.trim();
};
let httpProxy: string | undefined;
let httpsProxy: string | undefined;
if (field("HTTPEnable") === "1" && field("HTTPProxy")) {
const port = field("HTTPPort") || "80";
httpProxy = normalizeProxyUrl(`${field("HTTPProxy")}:${port}`, "http");
}
if (field("HTTPSEnable") === "1" && field("HTTPSProxy")) {
const port = field("HTTPSPort") || "443";
httpsProxy = normalizeProxyUrl(`${field("HTTPSProxy")}:${port}`, "http");
}
if (!httpProxy && !httpsProxy && field("SOCKSEnable") === "1" && field("SOCKSProxy")) {
const port = field("SOCKSPort") || "1080";
const socks = normalizeProxyUrl(`socks5://${field("SOCKSProxy")}:${port}`);
httpProxy = socks;
httpsProxy = socks;
}
if (!httpProxy && !httpsProxy) return undefined;
return { httpProxy: httpProxy ?? httpsProxy, httpsProxy: httpsProxy ?? httpProxy, source: "os" };
}
export function parseWindowsRegProxy(output: string): ProxySettings | undefined {
const enabledMatch = output.match(/^\s*ProxyEnable\s+REG_DWORD\s+(0x[0-9a-fA-F]+|\d+)\s*$/m);
if (!enabledMatch || Number(enabledMatch[1]) !== 1) return undefined;
const serverMatch = output.match(/^\s*ProxyServer\s+REG_SZ\s+(.+?)\s*$/m);
const rawServer = serverMatch?.[1]?.trim();
if (!rawServer) return undefined;
let httpProxy: string | undefined;
let httpsProxy: string | undefined;
let socksProxy: string | undefined;
if (rawServer.includes("=")) {
for (const part of rawServer.split(";")) {
const [k, v] = part.split("=", 2).map(s => s?.trim());
if (!k || !v) continue;
const lower = k.toLowerCase();
if (lower === "http") httpProxy = normalizeProxyUrl(v, "http");
else if (lower === "https") httpsProxy = normalizeProxyUrl(v, "http");
else if (lower === "socks") socksProxy = normalizeProxyUrl(v, "socks5");
}
} else {
httpProxy = normalizeProxyUrl(rawServer, "http");
httpsProxy = httpProxy;
}
httpProxy = httpProxy ?? httpsProxy ?? socksProxy;
httpsProxy = httpsProxy ?? httpProxy ?? socksProxy;
if (!httpProxy && !httpsProxy) return undefined;
const overrideMatch = output.match(/^\s*ProxyOverride\s+REG_SZ\s+(.+?)\s*$/m);
const noProxy = overrideMatch?.[1]
?.split(";")
.map(s => s.trim())
.filter(s => s && s.toLowerCase() !== "<local>" && !s.includes("*"))
.join(",");
return { httpProxy, httpsProxy, noProxy: noProxy || undefined, source: "os" };
}
function readOsSystemProxy(): ProxySettings | undefined {
const override = process.env.CYBERSTRIKE_OS_SYSTEM_PROXY_OVERRIDE;
if (override !== undefined) {
const normalized = normalizeProxyUrl(override);
return normalized ? { httpProxy: normalized, httpsProxy: normalized, source: "os" } : undefined;
}
if (process.env.CYBERSTRIKE_DISABLE_OS_PROXY === "1") return undefined;
const now = Date.now();
if (cachedOsProxy && now < cachedOsProxy.expiresAt) return cachedOsProxy.value;
let detected: ProxySettings | undefined;
try {
if (process.platform === "darwin") {
const out = execFileSync("scutil", ["--proxy"], { encoding: "utf8", timeout: 1_500, stdio: ["ignore", "pipe", "ignore"] });
detected = parseDarwinScutilProxy(out);
} else if (process.platform === "win32") {
const out = execFileSync("reg", ["query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"], {
encoding: "utf8",
timeout: 1_500,
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
detected = parseWindowsRegProxy(out);
}
} catch {
detected = undefined;
}
cachedOsProxy = { expiresAt: now + 30_000, value: detected };
return detected;
}
// Only retry errors that provably occurred before TLS handshake completion or
// TCP/CONNECT tunnel setup, where zero HTTP request bytes reached the origin.
export function isPreResponseConnectError(error: unknown): boolean {
@ -30,6 +349,7 @@ export function isPreResponseConnectError(error: unknown): boolean {
if (
message.includes("before secure tls connection was established") ||
message.includes("tls handshake") ||
message.includes("ssl routines") ||
message.includes("reset before headers") ||
message.includes("upstream connect") ||
code === "und_err_connect_timeout" ||
@ -64,6 +384,155 @@ function abortableDelay(ms: number, signal?: AbortSignal | null): Promise<void>
});
}
const ignoreUndiciDispatcherError = () => {};
function withUndiciErrorListener<T extends Dispatcher>(dispatcher: T): T {
if (dispatcher instanceof EventEmitter) {
EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError);
}
return dispatcher;
}
function createUndiciClient(origin: URL | string, options: Client.Options): Dispatcher {
return withUndiciErrorListener(new Client(origin, options));
}
function createUndiciOriginDispatcher(origin: URL | string, options: Pool.Options): Dispatcher {
if (options.connections === 1) {
return createUndiciClient(origin, options);
}
return withUndiciErrorListener(new Pool(origin, {
...options,
factory: createUndiciClient,
}));
}
function getDispatcherForProfile(profile: TransportProfile, proxy: ProxySettings): Dispatcher {
const key = `${profile.id}|${proxy.httpProxy ?? ""}|${proxy.httpsProxy ?? ""}|${proxy.noProxy ?? ""}`;
const existing = dispatcherCache.get(key);
if (existing) return existing;
const directConnectOpts = {
autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS,
ecdhCurve: CLASSIC_ECDH_CURVES,
...(profile.ipv4Only ? { family: 4, autoSelectFamily: false } : {}),
...(profile.allowH2 ? { preferH2: true } : {}),
...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}),
...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}),
...(profile.useCleanPublicDns ? { lookup: cleanPublicDnsLookup } : {}),
};
// Used by ProxyAgent / Socks5ProxyAgent when upgrading a tunnel socket to TLS.
const requestTlsOpts = {
ecdhCurve: CLASSIC_ECDH_CURVES,
ALPNProtocols: profile.allowH2 ? ["h2", "http/1.1"] : ["http/1.1"],
...(profile.allowH2 ? { preferH2: true } : {}),
...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}),
...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}),
} as unknown as EnvHttpProxyAgent.Options["requestTls"];
// Never set proxyTls unless the proxy itself uses https://. Undici's Socks5ProxyAgent
// treats any truthy proxyTls object as "connect to the SOCKS5 proxy over TLS".
const usesHttpsProxyServer = Boolean(
proxy.httpProxy?.toLowerCase().startsWith("https://") ||
proxy.httpsProxy?.toLowerCase().startsWith("https://"),
);
const proxyTlsOpts = usesHttpsProxyServer
? ({ autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS, ecdhCurve: CLASSIC_ECDH_CURVES } as unknown as EnvHttpProxyAgent.Options["proxyTls"])
: undefined;
const created = withUndiciErrorListener(new EnvHttpProxyAgent({
allowH2: profile.allowH2,
proxyTunnel: true,
connectTimeout: CONNECT_TIMEOUT_MS,
headersTimeout: 300_000,
bodyTimeout: 300_000,
httpProxy: proxy.httpProxy,
httpsProxy: proxy.httpsProxy,
...(proxy.noProxy !== undefined ? { noProxy: proxy.noProxy } : {}),
connect: directConnectOpts as unknown as EnvHttpProxyAgent.Options["connect"],
requestTls: requestTlsOpts,
...(proxyTlsOpts ? { proxyTls: proxyTlsOpts } : {}),
clientFactory: (origin, opts) => createUndiciOriginDispatcher(origin, opts as Pool.Options),
factory: createUndiciOriginDispatcher,
}));
dispatcherCache.set(key, created);
return created;
}
function matchesNoProxy(hostname: string, port: number, noProxy?: string): boolean {
if (!noProxy?.trim()) return false;
const host = hostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase();
for (const raw of noProxy.split(/[,\s]+/)) {
if (!raw) continue;
if (raw === "*") return true;
const m = raw.match(/^\*?\.?([^:]+?)(?::(\d+))?$/);
if (!m) continue;
const entryHost = m[1].replace(/\.$/, "").toLowerCase();
const entryPort = m[2] ? Number(m[2]) : 0;
if (entryPort && entryPort !== port) continue;
if (!raw.startsWith("*.") && host === entryHost) return true;
if (host.endsWith("." + entryHost)) return true;
}
return false;
}
function describeRoute(target: URL, proxy: ProxySettings): string {
const defaultPort = target.protocol === "https:" ? 443 : 80;
if (matchesNoProxy(target.hostname, Number(target.port) || defaultPort, proxy.noProxy)) {
return "direct";
}
const chosen = target.protocol === "https:" ? proxy.httpsProxy : proxy.httpProxy;
if (!chosen) return "direct";
try {
const parsed = new URL(chosen);
return `proxy ${parsed.protocol}//${parsed.host}`;
} catch {
return "proxy";
}
}
function annotateConnectError(error: unknown, target: URL, proxy: ProxySettings): unknown {
if (!(error instanceof Error)) return error;
const tag = `[endpoint=${target.host}, route=${describeRoute(target, proxy)}]`;
if (error.message.includes("[endpoint=")) return error;
const causeText = error.cause instanceof Error && error.cause.message && !error.message.includes(error.cause.message)
? `: ${error.cause.message}`
: "";
const wrapped = new Error(`${error.message}${causeText} ${tag}`, { cause: error });
const code = (error as NodeJS.ErrnoException).code ?? (error.cause as NodeJS.ErrnoException | undefined)?.code;
if (code) (wrapped as NodeJS.ErrnoException).code = code;
return wrapped;
}
function candidateStages(url: URL, envProxy: ProxySettings): { profile: TransportProfile; proxy: ProxySettings }[] {
const stages: { profile: TransportProfile; proxy: ProxySettings }[] = BASE_PROFILES.map(profile => ({ profile, proxy: envProxy }));
if (envProxy.source === "none" && !isLoopbackOrPrivateHost(url.hostname)) {
// Bypass stale Clash/Mihomo TUN Fake-IP (198.18.0.0/15) cached in OS or VMware NAT DNS
// after the user turns off their proxy client.
stages.push({ profile: DIRECT_CLEAN_DNS_PROFILE, proxy: DIRECT_PROXY_SETTINGS });
const osProxy = readOsSystemProxy();
if (osProxy) {
stages.push({ profile: OS_PROXY_PROFILE, proxy: osProxy });
}
} else if (
envProxy.source === "env" &&
isLocalClientProxy(envProxy) &&
isDomesticModelHost(url.hostname) &&
!matchesNoProxy(url.hostname, Number(url.port) || (url.protocol === "https:" ? 443 : 80), envProxy.noProxy)
) {
// When a local/LAN proxy client (e.g. Clash on 127.0.0.1 or VMware host 192.168.x.1)
// is turned off while HTTP_PROXY/HTTPS_PROXY remains in the shell environment, fall back
// to direct connection for official domestic model APIs such as DeepSeek.
stages.push({ profile: DIRECT_CLEAN_DNS_PROFILE, proxy: DIRECT_PROXY_SETTINGS });
}
const preferred = preferredProfileByOrigin.get(url.origin);
if (!preferred) return stages;
const idx = stages.findIndex(s => s.profile.id === preferred);
if (idx <= 0) return stages;
return [stages[idx], ...stages.slice(0, idx), ...stages.slice(idx + 1)];
}
async function fetchHop(
upstreamFetch: typeof fetch,
url: URL,
@ -72,8 +541,14 @@ async function fetchHop(
body: ArrayBuffer | undefined,
signal: AbortSignal | undefined,
): Promise<Response> {
for (let attempt = 0; ; attempt++) {
const envProxy = resolveEnvProxySettings();
const stages = candidateStages(url, envProxy);
let lastProxy = envProxy;
for (let attempt = 0; attempt < stages.length; attempt++) {
signal?.throwIfAborted?.();
const { profile, proxy } = stages[attempt];
lastProxy = proxy;
const dispatcher = getDispatcherForProfile(profile, proxy);
const request = new Request(url, {
method,
headers,
@ -82,14 +557,24 @@ async function fetchHop(
redirect: "manual",
});
try {
return await upstreamFetch(request);
const response = await upstreamFetch(request, { dispatcher } as RequestInit);
if (profile.id !== "default") {
preferredProfileByOrigin.set(url.origin, profile.id);
}
return response;
} catch (error) {
if (signal?.aborted || attempt >= PRE_TLS_RETRY_DELAYS_MS.length || !isPreResponseConnectError(error)) {
if (signal?.aborted || !isPreResponseConnectError(error)) {
throw error;
}
await abortableDelay(PRE_TLS_RETRY_DELAYS_MS[attempt], signal);
if (attempt >= stages.length - 1) {
const diagnosticProxy = envProxy.source === "env" ? envProxy : lastProxy;
throw annotateConnectError(error, url, diagnosticProxy);
}
const delay = PRE_TLS_RETRY_DELAYS_MS[Math.min(attempt, PRE_TLS_RETRY_DELAYS_MS.length - 1)];
await abortableDelay(delay, signal);
}
}
throw new Error(`Model connection failed [endpoint=${url.host}, route=${describeRoute(url, lastProxy)}]`);
}
async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Request, init?: RequestInit): Promise<Response> {
@ -118,43 +603,9 @@ async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Req
return blocked("redirect limit exceeded");
}
const ignoreUndiciDispatcherError = () => {};
function withUndiciErrorListener<T extends Dispatcher>(dispatcher: T): T {
if (dispatcher instanceof EventEmitter) {
EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError);
}
return dispatcher;
}
function createUndiciClient(origin: URL | string, options: Client.Options): Dispatcher {
return withUndiciErrorListener(new Client(origin, options));
}
function createUndiciOriginDispatcher(origin: URL | string, options: Pool.Options): Dispatcher {
if (options.connections === 1) {
return createUndiciClient(origin, options);
}
return withUndiciErrorListener(new Pool(origin, {
...options,
factory: createUndiciClient,
}));
}
export function installModelFetchPolicy(): void {
const tlsConnectOpts = { autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_TIMEOUT_MS };
const proxyConnectorOpts = tlsConnectOpts as unknown as EnvHttpProxyAgent.Options["proxyTls"];
setGlobalDispatcher(withUndiciErrorListener(new EnvHttpProxyAgent({
allowH2: false,
proxyTunnel: true,
headersTimeout: 300_000,
bodyTimeout: 300_000,
connect: tlsConnectOpts,
proxyTls: proxyConnectorOpts,
requestTls: proxyConnectorOpts,
clientFactory: (origin, opts) => createUndiciOriginDispatcher(origin, opts as Pool.Options),
factory: createUndiciOriginDispatcher,
})));
const envProxy = resolveEnvProxySettings();
setGlobalDispatcher(getDispatcherForProfile(BASE_PROFILES[0], envProxy));
// The Pi SDK does not run its CLI dispatcher setup. Install npm Undici's
// fetch and matching web types before wrapping fetch for the model SDKs.
install();

View File

@ -1,15 +1,27 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import dgram from "node:dgram";
import { createServer } from "node:http";
import { connect } from "node:net";
import { spawn } from "node:child_process";
import { createServer as createHttpsServer } from "node:https";
import { connect, createServer as createTcpServer } from "node:net";
import { execFileSync, spawn } from "node:child_process";
import { once } from "node:events";
import { mkdtemp, rm, readFile, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { fileURLToPath } from "node:url";
import { SessionManager } from "@earendil-works/pi-coding-agent";
import { isPreResponseConnectError } from "../dist/network.js";
import {
isDomesticModelHost,
isFakeIpAddress,
isLocalClientProxy,
isLoopbackOrPrivateHost,
isPreResponseConnectError,
normalizeProxyUrl,
parseDarwinScutilProxy,
parseWindowsRegProxy,
resolveEnvProxySettings,
} from "../dist/network.js";
import { RecordReader } from "../dist/protocol.js";
test("JSONL preserves Unicode separators and fragmented UTF-8", () => {
@ -814,3 +826,220 @@ test("generateOnly retries transient socket resets and fails over to backup chan
assert.ok(records.some(r => r.event?.type === "auto_retry_start"));
assert.ok(records.some(r => r.event?.type === "model_failover"));
});
test("proxy normalization covers ALL_PROXY, socks5h, schemeless host:port, and OS proxy parsers", () => {
assert.equal(normalizeProxyUrl("socks5h://127.0.0.1:7890"), "socks5://127.0.0.1:7890");
assert.equal(normalizeProxyUrl("127.0.0.1:7890"), "http://127.0.0.1:7890");
const envResolved = resolveEnvProxySettings({ ALL_PROXY: "socks5h://127.0.0.1:7890" });
assert.equal(envResolved.httpsProxy, "socks5://127.0.0.1:7890");
assert.equal(envResolved.source, "env");
assert.equal(isLoopbackOrPrivateHost("localhost"), true);
assert.equal(isLoopbackOrPrivateHost("192.168.1.10"), true);
assert.equal(isLoopbackOrPrivateHost("api.openai.com"), false);
const darwin = parseDarwinScutilProxy("{\n HTTPEnable : 1\n HTTPPort : 7890\n HTTPProxy : 127.0.0.1\n HTTPSEnable : 1\n HTTPSPort : 7890\n HTTPSProxy : 127.0.0.1\n}\n");
assert.equal(darwin?.httpsProxy, "http://127.0.0.1:7890");
const win = parseWindowsRegProxy("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\n ProxyEnable REG_DWORD 0x1\n ProxyServer REG_SZ 127.0.0.1:7890\n");
assert.equal(win?.httpsProxy, "http://127.0.0.1:7890");
});
test("TLS handshake keeps single-packet ClientHello, falls back to IPv4 on IPv6 TLS reset, and supports ALL_PROXY socks5h", { timeout: 45000 }, async t => {
const certDir = await mkdtemp(join(tmpdir(), "csai-pi-tls-cert-"));
t.after(() => rm(certDir, { recursive: true, force: true }));
const keyPath = join(certDir, "key.pem");
const certPath = join(certDir, "cert.pem");
execFileSync("openssl", [
"req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
"-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes",
"-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
], { stdio: "ignore" });
const key = await readFile(keyPath);
const cert = await readFile(certPath);
const httpsOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "tls-verified" }, "stop"));
httpsOrigin.listen(0, "127.0.0.1");
await once(httpsOrigin, "listening");
t.after(() => { httpsOrigin.closeAllConnections(); httpsOrigin.close(); });
const originPort = httpsOrigin.address().port;
// 1) Middlebox that sends TCP RST if ClientHello exceeds 600 bytes (rejects 1.6KB PQ ClientHello).
let clientHelloBytes = 0;
const middlebox = createTcpServer(client => {
client.once("data", firstChunk => {
clientHelloBytes = firstChunk.length;
if (firstChunk.length > 600) {
client.resetAndDestroy();
return;
}
const upstream = connect(originPort, "127.0.0.1", () => {
upstream.write(firstChunk);
client.pipe(upstream).pipe(client);
});
client.on("error", () => upstream.destroy());
upstream.on("error", () => client.destroy());
});
});
middlebox.listen(0, "127.0.0.1");
await once(middlebox, "listening");
t.after(() => middlebox.close());
const tlsEnv = { ...fixtureEnv, NODE_EXTRA_CA_CERTS: certPath, NO_PROXY: "localhost,127.0.0.1", no_proxy: "localhost,127.0.0.1" };
const compactRun = await invoke(t, { ...request(`https://localhost:${middlebox.address().port}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv);
assert.equal(compactRun.result.status, "completed", compactRun.result.error);
assert.equal(compactRun.result.response, "tls-verified");
assert.ok(clientHelloBytes > 0 && clientHelloBytes <= 600, `expected compact ClientHello <=600B, got ${clientHelloBytes}B`);
// 2) Dual-stack localhost where IPv6 (::1) accepts TCP then resets TLS, while IPv4 (127.0.0.1) serves HTTPS.
const v6Reset = createTcpServer(sock => sock.once("data", () => sock.resetAndDestroy()));
let ipv6Bound = true;
try {
v6Reset.listen(0, "::1");
await once(v6Reset, "listening");
} catch {
ipv6Bound = false;
}
if (ipv6Bound) {
t.after(() => v6Reset.close());
const dualPort = v6Reset.address().port;
const v4Https = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "ipv4-fallback-ok" }, "stop"));
v4Https.listen(dualPort, "127.0.0.1");
await once(v4Https, "listening");
t.after(() => { v4Https.closeAllConnections(); v4Https.close(); });
const dualRun = await invoke(t, { ...request(`https://localhost:${dualPort}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv);
assert.equal(dualRun.result.status, "completed", dualRun.result.error);
assert.equal(dualRun.result.response, "ipv4-fallback-ok");
}
// 3) Minimal SOCKS5 server exercised via ALL_PROXY=socks5h://127.0.0.1:<port> over HTTPS.
let socksConnections = 0;
const socksServer = createTcpServer(sock => {
socksConnections++;
sock.once("data", greeting => {
assert.equal(greeting[0], 0x05);
sock.write(Buffer.from([0x05, 0x00]));
sock.once("data", cmd => {
assert.equal(cmd[0], 0x05);
assert.equal(cmd[1], 0x01); // CONNECT
const atyp = cmd[3];
let offset = 4;
if (atyp === 0x01) offset += 4;
else if (atyp === 0x03) offset += 1 + cmd[4];
else if (atyp === 0x04) offset += 16;
const targetPort = cmd.readUInt16BE(offset);
const upstream = connect(targetPort, "127.0.0.1", () => {
sock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));
sock.pipe(upstream).pipe(sock);
});
sock.on("error", () => upstream.destroy());
upstream.on("error", () => sock.destroy());
});
});
});
socksServer.listen(0, "127.0.0.1");
await once(socksServer, "listening");
t.after(() => socksServer.close());
const socksEnv = {
...process.env,
NODE_EXTRA_CA_CERTS: certPath,
HTTP_PROXY: "", http_proxy: "", HTTPS_PROXY: "", https_proxy: "",
ALL_PROXY: `socks5h://127.0.0.1:${socksServer.address().port}`,
all_proxy: `socks5h://127.0.0.1:${socksServer.address().port}`,
NO_PROXY: "", no_proxy: "",
};
const socksRun = await invoke(t, { ...request(`https://localhost:${originPort}/v1`), generateOnly: true, tools: [] }, undefined, socksEnv);
assert.equal(socksRun.result.status, "completed", socksRun.result.error);
assert.equal(socksRun.result.response, "tls-verified");
assert.ok(socksConnections >= 1);
});
test("domestic DeepSeek endpoint recovers via clean DNS + direct fallback when local proxy is closed", { timeout: 45000 }, async t => {
assert.equal(isFakeIpAddress("198.18.0.45"), true);
assert.equal(isFakeIpAddress("198.19.255.1"), true);
assert.equal(isFakeIpAddress("8.8.8.8"), false);
assert.equal(isDomesticModelHost("api.deepseek.com"), true);
assert.equal(isDomesticModelHost("open.bigmodel.cn"), true);
assert.equal(isDomesticModelHost("api.openai.com"), false);
assert.equal(isLocalClientProxy({ httpsProxy: "http://192.168.33.1:7890", source: "env" }), true);
assert.equal(isLocalClientProxy({ httpsProxy: "http://proxy.corp.example.com:8080", source: "env" }), false);
const certDir = await mkdtemp(join(tmpdir(), "csai-pi-deepseek-cert-"));
t.after(() => rm(certDir, { recursive: true, force: true }));
const keyPath = join(certDir, "key.pem");
const certPath = join(certDir, "cert.pem");
execFileSync("openssl", [
"req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
"-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes",
"-subj", "/CN=api.deepseek.com",
"-addext", "subjectAltName=DNS:api.deepseek.com,IP:127.0.0.1",
], { stdio: "ignore" });
const key = await readFile(keyPath);
const cert = await readFile(certPath);
const deepseekOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "deepseek-direct-ok" }, "stop"));
deepseekOrigin.listen(0, "127.0.0.1");
await once(deepseekOrigin, "listening");
t.after(() => { deepseekOrigin.closeAllConnections(); deepseekOrigin.close(); });
// Local UDP DNS server answering A queries with 127.0.0.1.
let dnsQueries = 0;
const udpDns = dgram.createSocket("udp4");
udpDns.on("message", (msg, rinfo) => {
dnsQueries++;
const id = msg.subarray(0, 2);
let qEnd = 12;
while (qEnd < msg.length && msg[qEnd] !== 0) qEnd += 1 + msg[qEnd];
qEnd += 5; // null label + QTYPE(2) + QCLASS(2)
const question = msg.subarray(12, qEnd);
const header = Buffer.from([
id[0], id[1],
0x81, 0x80, // QR=1, RD=1, RA=1, NOERROR
0x00, 0x01, // QDCOUNT=1
0x00, 0x01, // ANCOUNT=1
0x00, 0x00, 0x00, 0x00,
]);
const answer = Buffer.from([
0xc0, 0x0c, // pointer to QNAME
0x00, 0x01, // TYPE A
0x00, 0x01, // CLASS IN
0x00, 0x00, 0x00, 0x3c, // TTL 60s
0x00, 0x04, // RDLENGTH 4
127, 0, 0, 1,
]);
udpDns.send(Buffer.concat([header, question, answer]), rinfo.port, rinfo.address);
});
udpDns.bind(0, "127.0.0.1");
await once(udpDns, "listening");
t.after(() => udpDns.close());
// Closed local proxy port (bind then immediately close so connect gets ECONNREFUSED).
const closedProxyProbe = createTcpServer();
closedProxyProbe.listen(0, "127.0.0.1");
await once(closedProxyProbe, "listening");
const deadProxyPort = closedProxyProbe.address().port;
await new Promise(r => closedProxyProbe.close(r));
const env = {
...process.env,
NODE_EXTRA_CA_CERTS: certPath,
HTTP_PROXY: `http://127.0.0.1:${deadProxyPort}`,
http_proxy: `http://127.0.0.1:${deadProxyPort}`,
HTTPS_PROXY: `http://127.0.0.1:${deadProxyPort}`,
https_proxy: `http://127.0.0.1:${deadProxyPort}`,
NO_PROXY: "",
no_proxy: "",
CYBERSTRIKE_CLEAN_DNS_SERVERS: `127.0.0.1:${udpDns.address().port}`,
};
const { result } = await invoke(
t,
{ ...request(`https://api.deepseek.com:${deepseekOrigin.address().port}/v1`), generateOnly: true, tools: [] },
undefined,
env,
);
assert.equal(result.status, "completed", result.error);
assert.equal(result.response, "deepseek-direct-ok");
assert.ok(dnsQueries >= 1);
});

View File

@ -77,7 +77,8 @@ function AssetLibraryWorkspace({ projectId, scope, projectResource, searchParams
const deepId = searchParams.get('id') || '';
const scopeQuery = useMemo(() => ({
project_id: projectId,
project_unassigned: scope === 'unassigned' ? true : undefined
project_unassigned: scope === 'unassigned' ? true : undefined,
sync_project_scope: projectId ? 1 : undefined
}), [projectId, scope]);
const [filters, setFilters] = useState(() => ({

View File

@ -376,9 +376,11 @@ export default function Page() {
if (lastActive.current === conversationId && !backgroundRunning) {
loadDetail(conversationId, { silent: true, force: true });
reloadConversations.current?.({ silent: true });
refreshHitl();
refreshPlan();
}
lastActive.current = backgroundRunning ? conversationId : null;
}, [backgroundRunning, conversationId, loadDetail]);
}, [backgroundRunning, conversationId, loadDetail, refreshHitl, refreshPlan]);
const stopTask = useCallback(async (targetId = '') => {
if (!canStop) return;
@ -395,9 +397,13 @@ export default function Page() {
await run.stop(requested);
await reloadActiveTasks.current?.({ silent: true, force: true });
reloadConversations.current?.({ silent: true });
refreshHitl();
refreshPlan();
setTimeout(() => {
reloadActiveTasks.current?.({ silent: true, force: true });
reloadConversations.current?.({ silent: true });
refreshHitl();
refreshPlan();
}, 950);
} finally {
if (effectiveId) {
@ -409,7 +415,7 @@ export default function Page() {
});
}
}
}, [canStop, live?.conversationId, run]);
}, [canStop, live?.conversationId, refreshHitl, refreshPlan, run]);
const selectConversation = useCallback(id => {
if (!id) return;

View File

@ -1,6 +1,6 @@
/** 新建深度测评表单:字段与 internal/handler/deep_assessment.go 的创建结构体一致。 */
import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { Banner, Button, Form, Spin, Typography } from '@douyinfe/semi-ui';
import { Banner, Button, Form, Spin, Tag, Typography } from '@douyinfe/semi-ui';
import { IconPlus } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { api } from '../../lib/http';
@ -59,13 +59,29 @@ function assessmentRoleOptions(raw) {
];
}
function formatScopeAssetLabel(asset) {
if (!asset || typeof asset !== 'object') return '';
const base = String(asset.domain || asset.ip || asset.host || '').trim();
if (!base) return '';
const port = Number(asset.port);
const hasPortInBase = base.includes(':') && !base.startsWith('[');
if (Number.isFinite(port) && port > 0 && !hasPortInBase) {
return `${base}:${port}`;
}
return base;
}
function ProjectAssetScope({ projectId }) {
const t = useT();
const assets = useResource(
() => api.get('/assets', { project_id: projectId, page: 1, page_size: 1 }),
() => api.get('/assets', { project_id: projectId, page: 1, page_size: 6, sync_project_scope: 1 }),
[projectId]
);
const total = Number.isFinite(Number(assets.data?.total)) ? Number(assets.data.total) : null;
const factCount = Number(assets.data?.project_fact_count) || 0;
const previewLabels = (Array.isArray(assets.data?.assets) ? assets.data.assets : [])
.map(formatScopeAssetLabel)
.filter(Boolean);
let message = t('common.loading', null, '加载中…');
if (!assets.loading && assets.error) {
message = '资产库暂时读不到。保存后仍使用该项目在资产库中的资产。';
@ -77,6 +93,23 @@ function ProjectAssetScope({ projectId }) {
return (
<Form.Slot label={t('deepAssessments.assetScope', null, '资产范围')}>
<Typography.Text type="tertiary" role="status">{message}</Typography.Text>
{!assets.loading && !assets.error && previewLabels.length > 0 ? (
<div className="assessment-scope-preview">
{previewLabels.map(label => (
<Tag key={label} size="small" color="light-blue">{label}</Tag>
))}
{total > previewLabels.length ? (
<Tag size="small" color="grey">{`+${total - previewLabels.length}`}</Tag>
) : null}
</div>
) : null}
{!assets.loading && !assets.error && total === 0 && factCount > 0 ? (
<div className="assessment-scope-hint">
<Typography.Text type="tertiary" size="small">
{`该项目已有 ${factCount} 条对话沉淀事实,测评启动时会自动带入上下文。`}
</Typography.Text>
</div>
) : null}
</Form.Slot>
);
}

View File

@ -206,6 +206,17 @@
padding-bottom: 0;
}
.assessment-scope-preview {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 8px;
}
.assessment-scope-hint {
margin-top: 6px;
}
.assessment-form-note {
margin-top: 8px;
}

View File

@ -1542,10 +1542,12 @@ test('deep assessment: create and select a new project without losing the draft'
const emptyScope = '这个项目的资产库还是空的。测评中新发现的目标会写进资产库,对话和批量任务也能看到。';
mockApi.respond('GET', '/api/assets', (_, url) => ({
json: {
assets: [],
assets: url.searchParams.get('project_id') === PROJECT.id
? [{ id: 'a1', domain: 'portal.example.com', port: 443 }, { id: 'a2', domain: 'api.example.com', port: 8443 }]
: [],
total: url.searchParams.get('project_id') === PROJECT.id ? 3 : 0,
page: 1,
page_size: 1
page_size: 6
}
}));
const main = await visit(page, 'deep-assessments');
@ -1566,7 +1568,13 @@ test('deep assessment: create and select a new project without losing the draft'
await page.getByRole('option').filter({ hasText: PROJECT.name }).click();
await expect(collectionSelect).toHaveCount(0);
await expect(drawer.getByRole('status')).toHaveText(sharedScope);
expect(mockApi.calls('GET', '/api/assets').some(call => new URLSearchParams(call.query).get('project_id') === PROJECT.id)).toBe(true);
await expect(drawer.locator('.assessment-scope-preview')).toContainText('portal.example.com:443');
await expect(drawer.locator('.assessment-scope-preview')).toContainText('api.example.com:8443');
await expect(drawer.locator('.assessment-scope-preview')).toContainText('+1');
expect(mockApi.calls('GET', '/api/assets').some(call => {
const q = new URLSearchParams(call.query);
return q.get('project_id') === PROJECT.id && q.get('sync_project_scope') === '1';
})).toBe(true);
expect(mockApi.calls('GET', '/api/assets/collections')).toEqual([]);
await createProject.click();
await expect(projectDrawer).toBeVisible();

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,Pt as s,R as c,U as l,ft as u,i as d,lt as f,ut as p}from"./semi-65W_4I1v.js";import{F as m,I as h,L as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-CAEPLS-g.js";var k=e(t(),1),A=e(n(),1),{Text:j}=r;function M(){let e=m(),{hasPermission:t}=h(),n=t(`agents:write`),r=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>g.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(c,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(u,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),r&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(a,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(l,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(d,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(d.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(d.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(d.Input,{field:`description`,label:`描述`}),(0,A.jsx)(d.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(d.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(d.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,Pt as s,R as c,U as l,ft as u,i as d,lt as f,ut as p}from"./semi-65W_4I1v.js";import{F as m,I as h,L as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-C6SML8F9.js";var k=e(t(),1),A=e(n(),1),{Text:j}=r;function M(){let e=m(),{hasPermission:t}=h(),n=t(`agents:write`),r=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>g.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await g.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await g.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await g.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(c,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(u,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),r&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(a,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(l,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(d,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(d.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(d.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(d.Input,{field:`description`,label:`描述`}),(0,A.jsx)(d.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(d.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(d.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,R as r}from"./semi-65W_4I1v.js";import{A as i,E as a,F as o}from"./index-CAEPLS-g.js";import"./c2-shared-Car3lDYq.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=t,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:t,ns:i=`tasks`}){let a=o();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:a(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(r,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>t(n.value),children:a(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=o();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:a(e),children:i(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,R as r}from"./semi-65W_4I1v.js";import{A as i,E as a,F as o}from"./index-C6SML8F9.js";import"./c2-shared-u6LJyEH4.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=t,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:t,ns:i=`tasks`}){let a=o();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:a(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(r,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>t(n.value),children:a(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=o();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:a(e),children:i(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

View File

@ -1 +1 @@
import{L as e,R as t}from"./index-CAEPLS-g.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
import{L as e,R as t}from"./index-C6SML8F9.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,R as s,U as c,lt as l,ut as u}from"./semi-65W_4I1v.js";import{E as d,F as f,I as p,L as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-CAEPLS-g.js";var T=e(t(),1),E=e(n(),1),{Text:D}=r;function O(){let e=f(),{hasPermission:t}=p(),n=t(`knowledge:delete`),[r,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>m.get(`/knowledge/retrieval-logs`,{conversationId:r||void 0,limit:k}),[r,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await m.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(s,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(a,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(c,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:r,onChange:O,style:{width:260}}),(0,E.jsx)(c,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,R as s,U as c,lt as l,ut as u}from"./semi-65W_4I1v.js";import{E as d,F as f,I as p,L as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-C6SML8F9.js";var T=e(t(),1),E=e(n(),1),{Text:D}=r;function O(){let e=f(),{hasPermission:t}=p(),n=t(`knowledge:delete`),[r,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>m.get(`/knowledge/retrieval-logs`,{conversationId:r||void 0,limit:k}),[r,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await m.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(s,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(a,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(c,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:r,onChange:O,style:{width:260}}),(0,E.jsx)(c,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,i}from"./semi-65W_4I1v.js";import{F as a,L as o,c as s,l as c,x as l}from"./index-CAEPLS-g.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=a(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await o.put(`/projects/${t.id}`,n):await o.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,i}from"./semi-65W_4I1v.js";import{F as a,L as o,c as s,l as c,x as l}from"./index-C6SML8F9.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=a(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await o.put(`/projects/${t.id}`,n):await o.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};

View File

@ -1,4 +1,4 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,g as r,t as i,y as a}from"./react-QV7DAAIx.js";import{$ as o,B as s,Ft as c,G as l,I as u,L as d,N as f,R as p,S as m,U as h,c as g,d as _,g as v,h as y,j as ee,k as b,lt as x,m as S,on as C,p as w,s as T,ut as E,y as D}from"./semi-65W_4I1v.js";import{D as O,E as k,F as te,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as G,u as K,x as ae,y as oe,z as se}from"./index-CAEPLS-g.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function Y(e){return JSON.stringify(String(e))}function me(e){let t=String(e);return pe(t)?t:Y(t)}function he(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):Y(String(e));let t=String(e);return pe(t)?t:Y(t)}function ge(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function _e(e,t,n,r){let i=` `.repeat(n),a=me(e);if(ge(t))r.push(`${i}${a}: ${he(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),be(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ve(t,n+2,r)):r.push(`${i}${a}: {}`)}function ve(e,t,n){for(let[r,i]of Object.entries(e))_e(r,i,t,n)}function ye(e,t,n){let r=` `.repeat(t);if(ge(e)){n.push(`${r}- ${he(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),be(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);ge(o)?n.push(`${r}- ${me(a)}: ${he(o)}`):(n.push(`${r}-`),_e(a,o,t+2,n));for(let[e,r]of s)_e(e,r,t+2,n)}function be(e,t,n){for(let r of e)ye(r,t,n)}function xe(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,g as r,t as i,y as a}from"./react-QV7DAAIx.js";import{$ as o,B as s,Ft as c,G as l,I as u,L as d,N as f,R as p,S as m,U as h,c as g,d as _,g as v,h as y,j as ee,k as b,lt as x,m as S,on as C,p as w,s as T,ut as E,y as D}from"./semi-65W_4I1v.js";import{D as O,E as k,F as te,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as G,u as K,x as ae,y as oe,z as se}from"./index-C6SML8F9.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function Y(e){return JSON.stringify(String(e))}function me(e){let t=String(e);return pe(t)?t:Y(t)}function he(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):Y(String(e));let t=String(e);return pe(t)?t:Y(t)}function ge(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function _e(e,t,n,r){let i=` `.repeat(n),a=me(e);if(ge(t))r.push(`${i}${a}: ${he(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),be(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ve(t,n+2,r)):r.push(`${i}${a}: {}`)}function ve(e,t,n){for(let[r,i]of Object.entries(e))_e(r,i,t,n)}function ye(e,t,n){let r=` `.repeat(t);if(ge(e)){n.push(`${r}- ${he(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),be(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);ge(o)?n.push(`${r}- ${me(a)}: ${he(o)}`):(n.push(`${r}-`),_e(a,o,t+2,n));for(let[e,r]of s)_e(e,r,t+2,n)}function be(e,t,n){for(let r of e)ye(r,t,n)}function xe(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
`).split(`
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return ge(e)?(n.push(he(e)),`${n.join(`
`)}\n`):Array.isArray(e)?(e.length?be(e,0,n):n.push(`[]`),`${n.join(`

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,Lt as r,R as i,ut as a}from"./semi-65W_4I1v.js";import{D as o,F as s,I as c,L as l,O as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-CAEPLS-g.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=t;function S(){let e=s(),{hasPermission:t}=c(),y=t(`skills:delete`),S=f(()=>l.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await l.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await l.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(i,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(i,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:u(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(r,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,Lt as r,R as i,ut as a}from"./semi-65W_4I1v.js";import{D as o,F as s,I as c,L as l,O as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-C6SML8F9.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=t;function S(){let e=s(),{hasPermission:t}=c(),y=t(`skills:delete`),S=f(()=>l.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await l.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await l.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(i,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(i,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:u(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(i,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(r,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};

File diff suppressed because one or more lines are too long

View File

@ -18,7 +18,7 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-CAEPLS-g.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-C6SML8F9.js"></script>
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-65W_4I1v.js">