Compare commits

..
Author SHA1 Message Date
ji ruo f7bf75f535 feat(agent): support reopening and steering tasks via resume_task, set_task_goals, and add_task_intent
- Add resume_task, set_task_goals, and add_task_intent orchestration tools bound to auto (and resume_task also bound to mainagent with task-context scoping) plus one-shot DB binding/prompt migrations.
- Wire task ID, NotifyGoal, and reviveTask into delegateToTask so set_task_goals and add_task_intent revive done/paused tasks in place while preserving graph/findings.
- Add shared resumeOrReopenTask and POST /api/tasks/{id}/resume (also wired into MCP resume_task) to reopen terminal tasks with open goals/intents and refuse closed tasks with no remaining work.
- Update auto and mainagent default prompts to prefer in-place resume/steering over spawning duplicate tasks.

Fixes #196
2026-11-27 15:31:16 +08:00
34 changed files with 818 additions and 680 deletions

No files matched your search

+7 -7
View File
@@ -21,14 +21,14 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
# 预装 Playwright MCP 与 CLI(全局),运行时优先直接调用 playwright-mcp,无需 npx 联网下载。
# 必须通过 playwright-mcp 自身的 install-browser 安装对应版本的 chromium 及其系统依赖,
# 避免全局 playwright 与 @playwright/mcp 内置 playwright-core 版本不一致导致找不到浏览器可执行文件。
RUN npm install -g @playwright/mcp@latest @playwright/cli@latest \
&& playwright-mcp --version \
# 预装 Playwright MCP 与 CLI(全局),运行时不再 npx 联网下载。
# @playwright/mcp:browser MCP 直接 `npx @playwright/mcp`(已全局装好,无需 -y/@latest)。
# @playwright/cli:提供 playwright-cli,装完顺带 --help 验证可执行。
# 再装 playwright(提供浏览器管理),装完用 --with-deps 预置 chromium 及其系统依赖,
# 这样容器内 MCP/CLI 首次启动即可用,不再联网下载浏览器。
RUN npm install -g @playwright/mcp@latest @playwright/cli@latest playwright@latest \
&& playwright-cli --help \
&& playwright-mcp install-browser --with-deps chromium \
&& playwright-cli install-browser chromium \
&& playwright install --with-deps chromium \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
ENV TZ=Asia/Shanghai
+1 -1
View File
@@ -121,7 +121,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
// visible skills/MCP and lets the DB tools table filter/override. DefaultTools
// have no tools-table rows, so they always pass through.
base := actool.DefaultTools()
ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID, WorkDir: sessionWorkDir})
ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID})
tools, def, cleanup := AugmentTools(ctx, agentKey, base)
defer cleanup()
+4 -3
View File
@@ -95,6 +95,7 @@ const mainAgentDefaultTmpl = `你是一个授权渗透测试系统的"主 agent"
**当任务目标已全部达成时**(graph_overview 里 goals 均为 met):下发前先判断这条意图背后是否隐含一个"新的、要达成的结果"。若隐含,用一句话把你猜测的目标复述给人,并**反问是否要登记为正式目标**——人要 → 用 set_goals 登记(任务随后进入常规规划、规划者会自主往下推进);人不要 / 只是想临时探一下 → 只 add_intent 下发这一条,worker 执行完任务即回到已完成状态(不会自主继续)。若这条意图明显只是一次性查证、不隐含新目标,直接 add_intent 即可,不必每次都问。
- 人想"对某条正在运行的意图(work)实时纠偏(别再走 X、聚焦 Y)" → 用 steer_work(不打断、不丢已有进展,worker 下一步动作前生效);先用 get_worker_output 看它在干嘛。方向整个错了则改用 add_intent 另下新意图。
- 人想"新增一个要达成的最终目标" → 用 set_goals 增补目标。系统会把该目标写入任务图并**自动把已完成/暂停的任务拉回运行态继续跑**(规划者随后会据此重新判断是否达成),无需人工再点恢复。
- 人想"恢复已暂停的任务,或重新打开已结束但仍有未完成目标/待执行(open)意图的任务" → 用 resume_task 原地将当前任务拉回运行态继续跑(保留已有探索图、发现与 frontier),不必新建重复任务。
- 人想"增/改测试约束(允许/禁止某类操作,如『仅测当前端口』『禁止爆破』『只做被动侦察』)" → 用 set_constraints 登记(type=allow 允许 / type=deny 禁止)。约束会在下一轮规划时注入 planner/worker 的提示词以框定探索边界;也可在总览「约束管理」里增删改。
3. 用人话简洁回复,说明你做了什么。
@@ -127,12 +128,12 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
// 领域工具 + 基础默认工具集(Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash)
// 资产覆盖度功能关闭时剔除 add_task_scope/list_untested_assets(不入 prompt)。
base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), actool.DefaultTools()...)
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
defer cleanup()
// 本任务的工作目录 <workDir>/tasks/<taskID>,先建好。
mainDir := ensureRunDir(m.workDir, taskID, 0)
ctx = intercept.WithReviewWorkingDirectory(ctx, mainDir)
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), WorkDir: mainDir})
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
defer cleanup()
system, boundary := deferredSystem(mainAgentSystem(goal, m.workDir, mainDir), def)
proxyAddr := m.proxyAddr
if m.proxyAddrFn != nil {
+4 -4
View File
@@ -375,10 +375,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
// 领域工具 + 基础默认工具集(Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash)
// 资产覆盖度功能关闭时剔除 add_task_scope/list_untested_assets(不入 prompt)。
base := append(tsx.DropCoverageTools(tsx.PlannerTools()), actool.DefaultTools()...)
// 本任务的工作目录 <workDir>/tasks/<taskID>,先建好。
taskDir := ensureRunDir(p.workDir, taskID, 0)
ctx = intercept.WithReviewContext(ctx, taskDir, intercept.ReviewBackground{})
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), WorkDir: taskDir})
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
tools, def, cleanup := AugmentTools(ctx, "planner", base)
defer cleanup()
// 关键态势(刚完成的意图 + 预取的完整图)改放【本轮 user 输入】(见下方 input),system
@@ -392,6 +389,9 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
if tc.Final {
situational += "\n\n【任务终局收尾(本轮特殊指令,覆盖上面的常规规划流程)】:" + resolveTaskTimeoutWrapup("planner")
}
// 本任务的工作目录 <workDir>/tasks/<taskID>,先建好。
taskDir := ensureRunDir(p.workDir, taskID, 0)
ctx = intercept.WithReviewContext(ctx, taskDir, intercept.ReviewBackground{})
sysBody := plannerSystem(goal, p.workDir, taskDir)
if p.wantConstraints() {
sysBody += constraintBlock(ts) // 操作约束(若有)注入系统提示,框定探索边界
+2 -1
View File
@@ -15,11 +15,12 @@ package agent
const autoDefaultTmpl = `你是 **Auto**,这个渗透测试平台的「操作助手」。你不亲自渗透,而是**用工具操作平台**、按用户指令把事情办好。
你能做的(取决于给你开放了哪些工具):
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、add_task_hint 给任务注入提示。
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、resume_task 恢复暂停任务或原地重新打开已结束且仍有未完成目标/待执行意图的任务、add_task_hint 给任务注入提示、set_task_goals 给任务增补最终目标(自动拉回运行态)、add_task_intent 给任务直投高优先级探索意图(自动拉回运行态)。
2. **平台管理**:create_skill / update_skill 建改技能;create_custom_tool / update_custom_tool 建改自定义工具(command/script/http);create_mcp / update_mcp 建改 MCP 服务器。
原则:
- 先看清现状(list_tasks / get_task_graph 等)再动手;一步到位、少空转。
- **原地继续优先于新建任务**:当用户要求继续、重开或补充已暂停/已结束的已有任务时,优先在原任务上操作(仍有 open 目标或 open 意图 → 用 resume_task 原地恢复;需要新增最终目标 → 用 set_task_goals;需要立刻测具体方向 → 用 add_task_intent),保留已有探索图与发现,不要用 spawn_task 新建重复任务。
- 涉及漏洞资产或拓扑时,优先使用用户引用快照中的 asset_topology.zone/zone_reason;三层区域含义固定为 internet(互联网入口)、boundary(公开暴露服务/应用/端点)、internal(私有地址及其业务资产)。不要仅凭 kind 改写区域,也不要把没有真实关系证据的跨区连接说成已验证通路。
- 建/改 skill、工具、MCP 时,把用户意图翻译成正确的结构化参数(kind/exec/schema 等),字段拿不准就按最小可用填。
- 用人话简洁汇报你做了什么、结果如何;只根据工具真实返回作答,不臆造。
-1
View File
@@ -20,7 +20,6 @@ type RunInfo struct {
ExplorationID int64 // exploration id; 0 when unknown
IntentID int64 // worker's intent node; 0 for planner/mainagent/chat
SessionID string // chat conversation id; empty for task runs
WorkDir string // active agent run working directory; used for stdio MCP CWD
}
// explorationID reads a store's exploration id, tolerating a nil store (planner and
+2
View File
@@ -221,6 +221,8 @@ func (t *ToolSet) ListWorkerTracesTool() actool.CoreTool { return t.listWorker
func (t *ToolSet) SearchWorkerTracesTool() actool.CoreTool { return t.searchAllWorkerTraces() }
func (t *ToolSet) NodeDetailTool() actool.CoreTool { return t.nodeDetail() }
func (t *ToolSet) AddHintTool() actool.CoreTool { return t.addHint() }
func (t *ToolSet) AddIntentTool() actool.CoreTool { return t.addIntent() }
func (t *ToolSet) SetGoalsTool() actool.CoreTool { return t.setGoals() }
// SetEnrich wires the async enrichment engine (DNS/HTTP auto-completion).
func (t *ToolSet) SetEnrich(e EnrichTrigger) { t.enrich = e }
+6 -6
View File
@@ -370,12 +370,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
// worker 刻意不给 MultiEdit/Glob/Grep:文件精改用 Edit、检索走 Bash(grep/find),
// 收敛工具面、减少低价值调用。其余 SDK 默认工具(Read/Write/Edit/LS/Bash/Sleep)照常。
base = append(base, defaultToolsExcept("MultiEdit", "Glob", "Grep")...)
// 本次意图的专属工作目录 <workDir>/tasks/<taskID>/i<intentID>,引擎侧先建好。
runDir := ensureRunDir(w.workDir, taskID, intent.ID)
// The run-wide intent is not the current tool action. Do not forward it or
// inherit a parent run's background into the action reviewer.
ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{})
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), IntentID: intent.ID, WorkDir: runDir})
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), IntentID: intent.ID})
tools, def, cleanup := AugmentTools(ctx, "worker", base)
defer cleanup()
@@ -385,6 +380,11 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
// 混入 per-intent 易变数据、失去跨意图缓存复用;这是刻意的取舍(意图丢失比省 token 严重得多)。
// 与 planner「态势块放 user turn」分叉是有意的:planner 本身是产意图的那个、没有单一 mandate,
// worker 有。仅【全局态势 overview】留在启动 user 消息里——它可降级、容忍 stale,压掉无碍。
// 本次意图的专属工作目录 <workDir>/tasks/<taskID>/i<intentID>,引擎侧先建好。
runDir := ensureRunDir(w.workDir, taskID, intent.ID)
// The run-wide intent is not the current tool action. Do not forward it or
// inherit a parent run's background into the action reviewer.
ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{})
overview := renderWorkerGraphOverview(tsx.graphOverviewData())
proxyAddr := w.proxyAddr
if w.proxyAddrFn != nil {
+4 -6
View File
@@ -77,15 +77,13 @@ func (d *DB) SetIntelligenceSettings(ctx context.Context, recording, enabled, bi
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7337741006)`); err != nil {
return err
}
record, on, bind := DefaultTaskIntelligence, false, false
record, on, bind := false, false, false
var value string
err = tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key=$1`, SettingTaskIntelligence).Scan(&value)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if err == nil {
record = value == "true" || value == "1"
}
record = value == "true" || value == "1"
if recording != nil {
record = *recording
}
@@ -142,7 +140,7 @@ func (d *DB) ClaimCredentialJob(ctx context.Context, bind bool, taskID int64) (*
defer tx.Rollback()
var id int64
err = tx.QueryRowContext(ctx, `SELECT i.id FROM task_intelligence i JOIN tasks t ON t.id=i.task_id
WHERE i.kind='credential' AND EXISTS(SELECT 1 FROM settings WHERE key='credential_agent_enabled' AND value IN ('true','1')) AND NOT EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value NOT IN ('true','1')) AND ($2::bigint=0 OR i.task_id=$2) AND t.deleted_at IS NULL AND t.archived_at IS NULL
WHERE i.kind='credential' AND EXISTS(SELECT 1 FROM settings WHERE key='credential_agent_enabled' AND value IN ('true','1')) AND EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value IN ('true','1')) AND ($2::bigint=0 OR i.task_id=$2) AND t.deleted_at IS NULL AND t.archived_at IS NULL
AND NOT EXISTS(SELECT 1 FROM task_archives a WHERE a.task_id=t.id AND a.state IN ('archive_queued','archiving','restore_queued','restoring','delete_queued','deleting'))
AND (i.credential_analysis IS NULL OR i.credential_analysis->>'state'='queued'
OR (i.credential_analysis->>'state'='processing' AND (i.credential_analysis->>'lease_until')::timestamptz < now())
@@ -179,7 +177,7 @@ func (d *DB) FinishCredentialJob(ctx context.Context, item *Intelligence, result
return err
}
var enabled, binding bool
if err = tx.QueryRowContext(ctx, `SELECT (EXISTS(SELECT 1 FROM settings WHERE key=$1 AND value IN ('true','1')) AND NOT EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value NOT IN ('true','1'))),EXISTS(SELECT 1 FROM settings WHERE key=$2 AND value IN ('true','1'))`, SettingCredentialAgent, SettingCredentialTraffic).Scan(&enabled, &binding); err != nil {
if err = tx.QueryRowContext(ctx, `SELECT (EXISTS(SELECT 1 FROM settings WHERE key=$1 AND value IN ('true','1')) AND EXISTS(SELECT 1 FROM settings WHERE key='task_intelligence_enabled' AND value IN ('true','1'))),EXISTS(SELECT 1 FROM settings WHERE key=$2 AND value IN ('true','1'))`, SettingCredentialAgent, SettingCredentialTraffic).Scan(&enabled, &binding); err != nil {
return err
}
if !enabled {
+1 -1
View File
@@ -12,7 +12,7 @@ func TestCredentialSwitchDependencyAndLeases(t *testing.T) {
t.Fatal(err)
}
defer d.Close()
oldRecording := d.GetBool(SettingTaskIntelligence, DefaultTaskIntelligence)
oldRecording := d.GetBool(SettingTaskIntelligence, false)
oldAgent, oldBinding := d.GetBool(SettingCredentialAgent, false), d.GetBool(SettingCredentialTraffic, false)
defer func() {
_ = d.SetBool(SettingTaskIntelligence, oldRecording)
+5 -6
View File
@@ -254,17 +254,16 @@ ON CONFLICT (agent_id, var_name) DO UPDATE
}
_ = d.SetSetting("interactive_shell_default_v1", "true")
}
// Seed the built-in browser (Playwright) MCP once — enabled by default for
// report reproduction screenshots, using Playwright's bundled Chromium rather
// than system Google Chrome. The traffic-capture toggle injects/strips the
// recording proxy + CA at runtime (server.Manager.syncBrowserMCPProxy).
// Seed the built-in browser (Playwright) MCP once — DISABLED by default (用户
// 需要时自行启用), no proxy by default. The traffic-capture toggle injects/strips
// the recording proxy + CA at runtime (server.Manager.syncBrowserMCPProxy).
// Insert only if absent so we never clobber user edits (args/env/enabled/
// visibility) on restart.
if _, err := d.Exec(`
INSERT INTO mcp_servers(name, transport, command, args, env, enabled)
VALUES ('browser', 'stdio', 'npx', $1, '{}', true)
VALUES ('browser', 'stdio', 'npx', $1, '{}', false)
ON CONFLICT (name) DO NOTHING`,
`["@playwright/mcp","--browser","chromium","--headless","--no-sandbox","--ignore-https-errors","--isolated"]`); err != nil {
`["@playwright/mcp","--headless"]`); err != nil {
return fmt.Errorf("seed browser mcp: %w", err)
}
// NOTE: the placeholder ScopeSentry data-source MCP (empty URL + empty X-API-Key,
+1 -4
View File
@@ -16,9 +16,6 @@ import (
const SettingTaskIntelligence = "task_intelligence_enabled"
// DefaultTaskIntelligence is the fallback for SettingTaskIntelligence when unset.
const DefaultTaskIntelligence = true
var ErrIntelligenceInvalid = errors.New("invalid intelligence")
var ErrIntelligenceNotFound = errors.New("intelligence not found")
@@ -240,7 +237,7 @@ func (d *DB) ListIntelligence(ctx context.Context, f IntelligenceFilter) (*Intel
if f.Offset < 0 {
f.Offset = 0
}
page := &IntelligencePage{Items: []*Intelligence{}, Counts: map[string]int{"credential": 0, "lead": 0, "sensitive_data": 0}, Enabled: d.GetBool(SettingTaskIntelligence, DefaultTaskIntelligence)}
page := &IntelligencePage{Items: []*Intelligence{}, Counts: map[string]int{"credential": 0, "lead": 0, "sensitive_data": 0}, Enabled: d.GetBool(SettingTaskIntelligence, false)}
page.CredentialAgentEnabled = d.GetBool(SettingCredentialAgent, false)
page.CredentialTrafficBinding = page.CredentialAgentEnabled && d.GetBool(SettingCredentialTraffic, false)
scope := intelligenceScope()
+6 -10
View File
@@ -23,7 +23,7 @@ import (
// hostTools, if set, returns runtime host tools (currently the traffic tools when
// capture is on) to add to EVERY agent's base list — the DB tools table then
// filters them per-agent binding. Empty/nil → no host tools this run (capture off).
func wireAgentAugment(pg *db.DB, skillDir, defaultWorkDir string, hostTools func() ([]actool.CoreTool, map[string][]string)) {
func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.CoreTool, map[string][]string)) {
agent.ToolAugment = func(ctx context.Context, agentKey string) ([]actool.CoreTool, agent.DeferredInfo, func()) {
a, err := pg.GetAgentByKey(agentKey)
if err != nil || a == nil {
@@ -84,11 +84,7 @@ func wireAgentAugment(pg *db.DB, skillDir, defaultWorkDir string, hostTools func
if !directVisible && !skillGated {
continue // neither directly visible nor referenced by a visible skill
}
mcpWorkDir := agent.RunInfoFrom(ctx).WorkDir
if mcpWorkDir == "" {
mcpWorkDir = defaultWorkDir
}
cl, err := connectMCP(ctx, m, mcpWorkDir)
cl, err := connectMCP(ctx, m)
if err != nil {
log.Printf("[mcp] %s 连接失败: %v", m.Name, err)
continue
@@ -104,7 +100,7 @@ func wireAgentAugment(pg *db.DB, skillDir, defaultWorkDir string, hostTools func
// it opt-in so a normal browser MCP session does not unexpectedly send
// image payloads to the model or consume extra tokens.
if m.Name == browserMCPName && isBrowserScreenshotTool(t.Name()) &&
(agentKey != "reporter" || !pg.GetBool(settingBrowserScreenshot, defaultBrowserScreenshot)) {
(agentKey != "reporter" || !pg.GetBool(settingBrowserScreenshot, false)) {
continue
}
extra = append(extra, t)
@@ -227,10 +223,10 @@ func seedPrompts(pg *db.DB) {
// flag and, if kept, wrapped so the model sees the DB-overridden description/schema
// and缺省入参 get injected. MCP/skill/host tools have no row and pass through.
func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) {
agent.FindingTrafficBindingEnabled = func() bool { return pg.GetBool(settingAgentTrafficBinding, defaultAgentTrafficBinding) }
agent.IntelligenceEnabled = func() bool { return pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) }
agent.FindingTrafficBindingEnabled = func() bool { return pg.GetBool(settingAgentTrafficBinding, false) }
agent.IntelligenceEnabled = func() bool { return pg.GetBool(db.SettingTaskIntelligence, false) }
agent.IntelligenceRecord = func(ctx context.Context, taskID, nodeID int64, worker string, input db.IntelligenceInput) (int64, error) {
if !pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) {
if !pg.GetBool(db.SettingTaskIntelligence, false) {
return 0, fmt.Errorf("任务情报自动记录已关闭")
}
item, err := pg.RecordIntelligence(ctx, taskID, nodeID, worker, input)
+1 -1
View File
@@ -48,7 +48,7 @@ func TestAssembleVisibleSkill(t *testing.T) {
t.Fatal(err)
}
wireAgentAugment(pg, skillDir, "", nil)
wireAgentAugment(pg, skillDir, nil)
t.Cleanup(func() { agent.ToolAugment = nil })
ag, _ := pg.GetAgentByKey("planner")
-180
View File
@@ -1,180 +0,0 @@
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
)
func TestEnsureBrowserMCPArgs(t *testing.T) {
got := ensureBrowserMCPArgs([]string{"@playwright/mcp", "--headless"}, true)
want := []string{"@playwright/mcp", "--headless", "--browser", "chromium", "--no-sandbox", "--ignore-https-errors", "--isolated"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("ensureBrowserMCPArgs(default) = %v, want %v", got, want)
}
// Idempotent on second call.
if again := ensureBrowserMCPArgs(got, true); !reflect.DeepEqual(again, want) {
t.Fatalf("ensureBrowserMCPArgs not idempotent: %v", again)
}
// Strips --user-data-dir when adding --isolated and respects explicit --browser.
custom := ensureBrowserMCPArgs([]string{"@playwright/mcp", "--browser", "firefox", "--user-data-dir", "/tmp/p", "--user-data-dir=/tmp/q"}, true)
for _, arg := range custom {
if strings.HasPrefix(arg, "--user-data-dir") || arg == "/tmp/p" {
t.Fatalf("stale user-data-dir remained: %v", custom)
}
if arg == "chromium" {
t.Fatalf("explicit --browser firefox was overwritten: %v", custom)
}
}
if !contains(custom, "--isolated") || !contains(custom, "--ignore-https-errors") || !contains(custom, "--no-sandbox") {
t.Fatalf("missing required flags: %v", custom)
}
}
func TestResolveStdioMCPCommand(t *testing.T) {
orig := lookPath
t.Cleanup(func() { lookPath = orig })
lookPath = func(file string) (string, error) {
if file == "playwright-mcp" {
return "/usr/local/bin/playwright-mcp", nil
}
return "", errors.New("not found")
}
cmd, args := resolveStdioMCPCommand("npx", []string{"-y", "@playwright/mcp", "--browser", "chromium", "--headless"})
if cmd != "/usr/local/bin/playwright-mcp" || !reflect.DeepEqual(args, []string{"--browser", "chromium", "--headless"}) {
t.Fatalf("container path: got (%q, %v)", cmd, args)
}
lookPath = func(string) (string, error) { return "", errors.New("not found") }
cmd, args = resolveStdioMCPCommand("npx", []string{"@playwright/mcp", "--browser", "chromium"})
if cmd != "npx" || !reflect.DeepEqual(args, []string{"-y", "@playwright/mcp", "--browser", "chromium"}) {
t.Fatalf("npx fallback: got (%q, %v)", cmd, args)
}
// Unrelated npx packages and non-npx commands pass through unchanged.
cmd, args = resolveStdioMCPCommand("npx", []string{"some-other-mcp", "--flag"})
if cmd != "npx" || !reflect.DeepEqual(args, []string{"some-other-mcp", "--flag"}) {
t.Fatalf("other npx package modified: got (%q, %v)", cmd, args)
}
}
func TestStdioMCPClientUsesWorkingDirectoryAndCapturesStderr(t *testing.T) {
workDir := t.TempDir()
script := filepath.Join(t.TempDir(), "fake-mcp.sh")
body := `#!/bin/sh
while IFS= read -r line; do
case "$line" in
*'"method":"initialize"'*)
printf '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"fake","version":"1"}}}\n'
;;
*'"method":"tools/list"'*)
printf '{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"browser_take_screenshot","description":"save shot","inputSchema":{"type":"object"}}]}}\n'
;;
*'"method":"tools/call"'*)
mkdir -p findings/screenshots
printf 'png-bytes' > findings/screenshots/finding-7-step-1.png
printf '{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"saved in %s"}]}}\n' "$(pwd)"
;;
esac
done
`
if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cl, err := newStdioMCPClient(ctx, "browser", workDir, script, nil)
if err != nil {
t.Fatalf("newStdioMCPClient: %v", err)
}
defer cl.Close()
tools, err := cl.Tools(ctx)
if err != nil || len(tools) != 1 || tools[0].Name() != "mcp__browser__browser_take_screenshot" {
t.Fatalf("tools = %v, err = %v", tools, err)
}
res, err := tools[0].Call(ctx, json.RawMessage(`{"filename":"findings/screenshots/finding-7-step-1.png"}`), nil)
if err != nil || res.IsError {
t.Fatalf("tool call failed: res=%+v err=%v", res, err)
}
shotPath := filepath.Join(workDir, "findings", "screenshots", "finding-7-step-1.png")
data, err := os.ReadFile(shotPath)
if err != nil || string(data) != "png-bytes" {
t.Fatalf("screenshot not written in workDir (%s): data=%q err=%v", shotPath, string(data), err)
}
// Verify stderr is surfaced when a stdio MCP crashes before handshake.
failScript := filepath.Join(t.TempDir(), "fail-mcp.sh")
if err := os.WriteFile(failScript, []byte("#!/bin/sh\necho 'boom: chrome missing' >&2\nexit 1\n"), 0o755); err != nil {
t.Fatal(err)
}
if _, err := newStdioMCPClient(ctx, "browser", workDir, failScript, nil); err == nil || !strings.Contains(err.Error(), "boom: chrome missing") {
t.Fatalf("expected stderr in error, got: %v", err)
}
}
func TestDefaultEnabledSettingsAndScreenshotTimestampHeader(t *testing.T) {
s, _, request := trafficEvidenceServer(t)
pg := s.m.pg
keys := []string{
settingBrowserScreenshot,
settingScreenshotTimestamp,
settingAgentTrafficBinding,
db.SettingTaskIntelligence,
}
for _, k := range keys {
if _, err := pg.Exec(`DELETE FROM settings WHERE key=$1`, k); err != nil {
t.Fatal(err)
}
key := k
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM settings WHERE key=$1`, key) })
}
payload := s.settingsPayload()
for _, k := range keys {
if payload[k] != true {
t.Fatalf("expected %s to default to true, got %v", k, payload[k])
}
}
// With task_intelligence_enabled unset (default true), enabling credential_agent_enabled must succeed.
t.Cleanup(func() {
_, _ = pg.Exec(`DELETE FROM settings WHERE key IN ($1,$2,$3)`, db.SettingTaskIntelligence, db.SettingCredentialAgent, db.SettingCredentialTraffic)
})
if r := request("PUT", "/api/settings", `{"credential_agent_enabled":true}`); r.Code != 200 {
t.Fatalf("enabling credential_agent_enabled under default task_intelligence_enabled failed: %d %s", r.Code, r.Body.String())
}
// Archived screenshot under tasks/<id>/findings/screenshots/ previews with timestamp header by default.
shot := filepath.Join(s.m.dir, "tasks", "99", "findings", "screenshots", "finding-99-step-1.png")
if err := os.MkdirAll(filepath.Dir(shot), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(shot, []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, 0o644); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/workspace/preview?path=findings/screenshots/finding-99-step-1.png", nil)
s.wsPreview(rec, req)
if rec.Code != 200 {
t.Fatalf("wsPreview status = %d, body = %s", rec.Code, rec.Body.String())
}
if rec.Header().Get("X-Report-Screenshot-Timestamp") == "" {
t.Fatal("expected X-Report-Screenshot-Timestamp header when setting is unset (default true)")
}
}
+4 -4
View File
@@ -53,7 +53,7 @@ func (s *Server) runCredentialProcessor() {
case <-ticker.C:
case <-s.credentialWake:
}
if !s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, false) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
continue
}
a, err := s.m.pg.GetAgentByKey(db.CredentialAgentKey)
@@ -74,7 +74,7 @@ func (s *Server) runCredentialProcessor() {
}
}
func (s *Server) processCredentialJob(parent context.Context, item *db.Intelligence) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, false) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
_ = s.m.pg.FinishCredentialJob(parent, item, *item.Credentials)
return
}
@@ -89,7 +89,7 @@ func (s *Server) processCredentialJob(parent context.Context, item *db.Intellige
case <-ctx.Done():
return
case <-tick.C:
if !s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, false) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
cancel()
return
}
@@ -401,7 +401,7 @@ func (s *Server) matchCredentialTraffic(ctx context.Context, item *db.Intelligen
}
func (s *Server) retryCredentials(w http.ResponseWriter, r *http.Request) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
if !s.m.pg.GetBool(db.SettingTaskIntelligence, false) || !s.m.pg.GetBool(db.SettingCredentialAgent, false) {
writeErr(w, 409, "请先开启 Agent 开关")
return
}
+3 -4
View File
@@ -37,7 +37,7 @@ func TestCredentialProcessingFlowBindingAndScopes(t *testing.T) {
t.Fatal(err)
}
taskID := *f.TaskID
oldRecording := s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence)
oldRecording := s.m.pg.GetBool(db.SettingTaskIntelligence, false)
oldOn, oldBind := s.m.pg.GetBool(db.SettingCredentialAgent, false), s.m.pg.GetBool(db.SettingCredentialTraffic, false)
defer func() {
_ = s.m.pg.SetBool(db.SettingTaskIntelligence, oldRecording)
@@ -46,7 +46,6 @@ func TestCredentialProcessingFlowBindingAndScopes(t *testing.T) {
_ = s.m.pg.SetCredentialAgentSettings(t.Context(), nil, &oldBind)
}
}()
_ = s.m.pg.SetBool(db.SettingTaskIntelligence, false)
_ = s.m.pg.SetBool(db.SettingCredentialAgent, false)
_ = s.m.pg.SetBool(db.SettingCredentialTraffic, false)
if r := request("PUT", "/api/settings", `{"credential_traffic_binding":true}`); r.Code != 400 {
@@ -210,7 +209,7 @@ func TestCredentialDisableCancelsInFlightModel(t *testing.T) {
t.Fatal(err)
}
taskID := *finding.TaskID
oldRecording := s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence)
oldRecording := s.m.pg.GetBool(db.SettingTaskIntelligence, false)
oldOn, oldBinding := s.m.pg.GetBool(db.SettingCredentialAgent, false), s.m.pg.GetBool(db.SettingCredentialTraffic, false)
defer func() {
_ = s.m.pg.SetBool(db.SettingTaskIntelligence, oldRecording)
@@ -275,7 +274,7 @@ func TestCredentialFailedModelCanRetry(t *testing.T) {
t.Fatal(err)
}
taskID := *finding.TaskID
oldRecord, oldAgent, oldBind := s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence), s.m.pg.GetBool(db.SettingCredentialAgent, false), s.m.pg.GetBool(db.SettingCredentialTraffic, false)
oldRecord, oldAgent, oldBind := s.m.pg.GetBool(db.SettingTaskIntelligence, false), s.m.pg.GetBool(db.SettingCredentialAgent, false), s.m.pg.GetBool(db.SettingCredentialTraffic, false)
defer s.m.pg.SetIntelligenceSettings(t.Context(), &oldRecord, &oldAgent, &oldBind)
on, off := true, false
_ = s.m.pg.SetIntelligenceSettings(t.Context(), &on, &on, &off)
+1 -1
View File
@@ -151,7 +151,7 @@ func (s *Server) toolBindFindingTraffic() actool.CoreTool {
return wrTool("bind_finding_traffic", "为已登记漏洞补绑经核实的真实 HTTP 流量。finding_id 使用独立漏洞记录 ID;不要传探索节点 ID。同批引用全部成功或全部失败,重复引用不覆盖已有说明。补绑会使已有报告标记待更新;不要为补包重新探测或重复创建漏洞。",
objSchema(map[string]any{"finding_id": strParam("独立漏洞记录 ID,从 list_task_findings / get_task_node_detail 的 finding_id 字段读取"), "traffic_refs": agent.HintTrafficSchema()}, "finding_id", "traffic_refs"),
func(ctx context.Context, raw json.RawMessage) (actool.Result, error) {
if !s.m.pg.GetBool(settingAgentTrafficBinding, defaultAgentTrafficBinding) {
if !s.m.pg.GetBool(settingAgentTrafficBinding, false) {
return actool.Errorf("Agent 自动绑定流量已关闭;请在系统设置开启,或使用页面人工绑定。"), nil
}
var args struct {
+4 -10
View File
@@ -44,9 +44,9 @@ func TestFindingWorkflowAutoHintToPlannerAndSetting(t *testing.T) {
if _, err := pg.Exec(`DELETE FROM settings WHERE key=$1`, settingAgentTrafficBinding); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM settings WHERE key=$1`, settingAgentTrafficBinding) })
if s.settingsPayload()[settingAgentTrafficBinding] != true {
t.Fatal("missing setting must default on")
t.Cleanup(func() { pg.SetBool(settingAgentTrafficBinding, false) })
if s.settingsPayload()[settingAgentTrafficBinding] != false {
t.Fatal("missing setting must default off")
}
seedServerEvidenceFlow(t, s, "handoff-proof", []byte("verified local proof"))
seedServerEvidenceFlow(t, s, "handoff-baseline", []byte("local baseline"))
@@ -55,19 +55,13 @@ func TestFindingWorkflowAutoHintToPlannerAndSetting(t *testing.T) {
if r := request("POST", fmt.Sprintf("/api/exploration/findings/%d/traffic", initial.FindingID), `{"traffic_refs":[{"traffic_id":"handoff-proof"}]}`); r.Code != 200 {
t.Fatal(r.Code, r.Body)
}
if r := request("PUT", "/api/settings", `{"agent_traffic_binding":false}`); r.Code != 200 {
t.Fatal(r.Code, r.Body)
}
if pg.GetBool(settingAgentTrafficBinding, defaultAgentTrafficBinding) {
t.Fatal("disable switch was not persisted")
}
bind := s.toolBindFindingTraffic()
input := map[string]any{"finding_id": initial.FindingID, "traffic_refs": []db.TrafficRef{{TrafficID: "handoff-baseline"}}}
workflowCall(t, ctx, bind, input, true)
if r := request("PUT", "/api/settings", `{"agent_traffic_binding":true}`); r.Code != 200 {
t.Fatal(r.Code, r.Body)
}
if !pg.GetBool(settingAgentTrafficBinding, defaultAgentTrafficBinding) {
if !pg.GetBool(settingAgentTrafficBinding, false) {
t.Fatal("switch was not persisted")
}
f, _ := pg.GetFinding(initial.FindingID)
+4 -13
View File
@@ -15,12 +15,8 @@ func TestIntelligenceHTTPSettingsAndScope(t *testing.T) {
t.Fatal(err)
}
taskID := *f.TaskID
if _, err := s.m.pg.Exec(`DELETE FROM settings WHERE key=$1`, db.SettingTaskIntelligence); err != nil {
t.Fatal(err)
}
defer s.m.pg.Exec(`DELETE FROM settings WHERE key=$1`, db.SettingTaskIntelligence)
if s.settingsPayload()[db.SettingTaskIntelligence] != true {
t.Fatal("default must be on")
if s.settingsPayload()[db.SettingTaskIntelligence] != false {
t.Fatal("default must be off")
}
if s.settingsPayload()[db.SettingTaskAutoTitle] != false || s.settingsPayload()[db.SettingChatAutoTitle] != false {
t.Fatal("auto title settings must default to off")
@@ -33,16 +29,11 @@ func TestIntelligenceHTTPSettingsAndScope(t *testing.T) {
}
defer s.m.pg.SetBool(db.SettingTaskAutoTitle, false)
defer s.m.pg.SetBool(db.SettingChatAutoTitle, false)
if r := request("PUT", "/api/settings", `{"task_intelligence_enabled":false}`); r.Code != 200 {
t.Fatal(r.Code, r.Body)
}
if s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) {
t.Fatal("disable setting not persisted")
}
if r := request("PUT", "/api/settings", `{"task_intelligence_enabled":true}`); r.Code != 200 {
t.Fatal(r.Code, r.Body)
}
if !s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence) {
defer s.m.pg.SetBool(db.SettingTaskIntelligence, false)
if !s.m.pg.GetBool(db.SettingTaskIntelligence, false) {
t.Fatal("setting not persisted")
}
in := db.IntelligenceInput{Kind: "credential", Title: "test credential", Content: "local-api-fixture-secret", Evidence: "local fixture evidence", Confidence: "observed"}
+4 -15
View File
@@ -374,10 +374,6 @@ const (
// defaultConcurrencyLimit is the simultaneous-running-task cap when the feature
// is enabled but no explicit limit was saved.
defaultConcurrencyLimit = 5
// Default states for core evidence/intelligence toggles when unset in DB.
defaultBrowserScreenshot = true
defaultScreenshotTimestamp = true
defaultAgentTrafficBinding = true
)
// WorkerPool binds a number of worker slots to one LLM profile. Profile IDs are
@@ -934,12 +930,11 @@ func (m *Manager) syncBrowserMCPProxy() {
proxy := m.ProxyAddr() // "" when capture off
cert := m.ProxyCACert() // "" when capture off
screenshotOn := m.pg.GetBool(settingBrowserScreenshot, defaultBrowserScreenshot)
args := ensureBrowserMCPArgs(stripProxyArgs(decodeStrSlice(srv.Args)), screenshotOn)
args := ensureBrowserMCPArgs(stripProxyArgs(decodeStrSlice(srv.Args)), m.pg.GetBool(settingBrowserScreenshot, false))
env := decodeStrMap(srv.Env)
if screenshotOn {
// Keep the built-in browser MCP enabled when screenshots are active
// (including default-on after upgrade from an older DB where it was seeded disabled).
if m.pg.GetBool(settingBrowserScreenshot, false) {
// A persisted screenshot opt-in must survive restart even if an older
// database had the seeded MCP disabled.
srv.Enabled = true
}
delete(env, "NODE_EXTRA_CA_CERTS")
@@ -980,12 +975,6 @@ func ensureBrowserMCPArgs(args []string, screenshotEnabled bool) []string {
}
return false
}
if !has("--browser") {
// @playwright/mcp defaults to channel="chrome" (/opt/google/chrome/chrome),
// which is absent in slim/arm64 containers. Explicitly select Playwright's
// bundled Chromium unless the user configured another browser.
out = append(out, "--browser", "chromium")
}
if !has("--headless") {
out = append(out, "--headless")
}
+11 -3
View File
@@ -140,8 +140,8 @@ func (s *Server) mcpTools() []mcpTool {
},
{
Name: "resume_task", Scope: db.APIScopeTaskControl,
Description: "恢复已暂停的任务。并发已满时任务会进入排队(status=queued)。",
Schema: objSchema(map[string]any{"task_id": strParam("要恢复的任务 id")}, "task_id"),
Description: "恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务。并发已满时任务会进入排队(status=queued)。",
Schema: objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id")}, "task_id"),
Run: func(_ context.Context, token *db.APIToken, in json.RawMessage) (actool.Result, error) {
return s.mcpControlTask(token, in, "resume")
},
@@ -524,7 +524,15 @@ func (s *Server) mcpControlTask(token *db.APIToken, in json.RawMessage, action s
if t == nil {
return failure, nil
}
out, err := s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
var (
out taskControlResult
err error
)
if action == "resume" {
out, err = s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
} else {
out, err = s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
}
if err != nil {
return actool.Errorf(err.Error()), nil
}
+4 -54
View File
@@ -4,13 +4,11 @@ import (
"context"
"fmt"
"log"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/mcphttp"
"github.com/Autumn-27/norma/mcp"
actool "github.com/Autumn-27/norma/tool"
)
@@ -22,62 +20,14 @@ type mcpClient interface {
Close() error
}
var lookPath = exec.LookPath
// resolveStdioMCPCommand prefers a locally installed playwright-mcp binary
// when an MCP server is configured as `npx @playwright/mcp ...`. In Docker
// images where `@playwright/mcp` is globally installed, calling the binary
// directly avoids `npx` trying to hit the registry or prompting on stdin; when
// falling back to `npx`, inject `-y` so it never blocks waiting for consent.
func resolveStdioMCPCommand(command string, args []string) (string, []string) {
out := append([]string(nil), args...)
if filepath.Base(strings.TrimSpace(command)) != "npx" {
return command, out
}
pkgIdx := -1
hasYes := false
for i, arg := range out {
if arg == "-y" || arg == "--yes" {
hasYes = true
continue
}
if strings.HasPrefix(arg, "-") {
continue
}
if arg == "@playwright/mcp" || strings.HasPrefix(arg, "@playwright/mcp@") {
pkgIdx = i
}
break
}
if pkgIdx < 0 {
return command, out
}
if bin, err := lookPath("playwright-mcp"); err == nil && strings.TrimSpace(bin) != "" {
rest := make([]string, 0, len(out)-1)
for i, arg := range out {
if i == pkgIdx || (i < pkgIdx && (arg == "-y" || arg == "--yes")) {
continue
}
rest = append(rest, arg)
}
return bin, rest
}
if !hasYes {
out = append([]string{"-y"}, out...)
}
return command, out
}
// connectMCP dials one MCP server per its transport. Callers must Close the client.
// workDir sets the subprocess working directory for stdio MCP servers when non-empty.
func connectMCP(ctx context.Context, m *db.MCPServer, workDir string) (mcpClient, error) {
func connectMCP(ctx context.Context, m *db.MCPServer) (mcpClient, error) {
switch m.Transport {
case "stdio":
if m.Command == "" {
return nil, fmt.Errorf("stdio 传输缺少命令")
}
cmd, args := resolveStdioMCPCommand(m.Command, jsonStrSlice(m.Args))
return newStdioMCPClient(ctx, m.Name, workDir, cmd, jsonStrMap(m.Env), args...)
return mcp.NewStdioClient(ctx, m.Name, m.Command, jsonStrMap(m.Env), jsonStrSlice(m.Args)...)
case "http":
if m.URL == "" {
return nil, fmt.Errorf("http 传输缺少 URL")
@@ -97,7 +47,7 @@ func connectMCP(ctx context.Context, m *db.MCPServer, workDir string) (mcpClient
// discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool
// names to mcp_tools_cache so the UI shows them without a live connection.
func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error {
cl, err := connectMCP(ctx, m, s.m.dir)
cl, err := connectMCP(ctx, m)
if err != nil {
return err
}
-296
View File
@@ -1,296 +0,0 @@
package server
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/mcp"
"github.com/Autumn-27/norma/permission"
actool "github.com/Autumn-27/norma/tool"
)
type stdioRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id,omitempty"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
}
type stdioRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Error *stdioRPCError `json:"error"`
}
type stdioRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *stdioRPCError) Error() string {
return fmt.Sprintf("mcp rpc error %d: %s", e.Code, e.Message)
}
type stdioRemoteTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
}
// tailBuffer keeps the last limit bytes written to it so child-process stderr
// can surface actionable diagnostics without unbounded memory growth.
type tailBuffer struct {
mu sync.Mutex
limit int
buf []byte
}
func newTailBuffer(limit int) *tailBuffer {
return &tailBuffer{limit: limit}
}
func (t *tailBuffer) Write(p []byte) (int, error) {
t.mu.Lock()
defer t.mu.Unlock()
if len(p) >= t.limit {
t.buf = append(t.buf[:0], p[len(p)-t.limit:]...)
return len(p), nil
}
if excess := len(t.buf) + len(p) - t.limit; excess > 0 {
copy(t.buf, t.buf[excess:])
t.buf = t.buf[:len(t.buf)-excess]
}
t.buf = append(t.buf, p...)
return len(p), nil
}
func (t *tailBuffer) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return strings.TrimSpace(string(t.buf))
}
// stdioMCPClient speaks JSON-RPC 2.0 over newline-delimited stdio to a child
// MCP server spawned in an explicit working directory (so file-writing tools
// such as Playwright's browser_take_screenshot resolve relative paths inside
// the active agent session/workspace rather than the server binary's CWD).
type stdioMCPClient struct {
server string
w io.Writer
mu sync.Mutex
nextID int
pending map[int]chan stdioRPCResponse
closeCh chan struct{}
once sync.Once
cmd *exec.Cmd
stdin io.Closer
stderr *tailBuffer
closeOnce sync.Once
}
func newStdioMCPClient(ctx context.Context, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) {
cmd := exec.Command(command, args...)
if strings.TrimSpace(workDir) != "" {
cmd.Dir = workDir
}
if len(env) > 0 {
cmd.Env = os.Environ()
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr := newTailBuffer(4096)
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return nil, err
}
c := &stdioMCPClient{
server: server,
w: stdin,
pending: map[int]chan stdioRPCResponse{},
closeCh: make(chan struct{}),
cmd: cmd,
stdin: stdin,
stderr: stderr,
}
go c.readLoop(stdout)
if err := c.initialize(ctx); err != nil {
_ = c.Close()
return nil, err
}
return c, nil
}
func (c *stdioMCPClient) readLoop(r io.Reader) {
br := bufio.NewReaderSize(r, 64*1024)
for {
line, err := br.ReadBytes('\n')
line = bytes.TrimSpace(line)
if len(line) > 0 {
var resp stdioRPCResponse
if json.Unmarshal(line, &resp) == nil && resp.ID != 0 {
c.mu.Lock()
ch := c.pending[resp.ID]
delete(c.pending, resp.ID)
c.mu.Unlock()
if ch != nil {
ch <- resp
}
}
}
if err != nil {
if !errors.Is(err, io.EOF) {
break
}
break
}
}
c.once.Do(func() { close(c.closeCh) })
}
func (c *stdioMCPClient) writeLocked(v any) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
data = append(data, '\n')
_, err = c.w.Write(data)
return err
}
func (c *stdioMCPClient) notify(method string, params any) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.writeLocked(stdioRPCRequest{JSONRPC: "2.0", Method: method, Params: params})
}
func (c *stdioMCPClient) call(ctx context.Context, method string, params any) (json.RawMessage, error) {
c.mu.Lock()
c.nextID++
id := c.nextID
ch := make(chan stdioRPCResponse, 1)
c.pending[id] = ch
err := c.writeLocked(stdioRPCRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params})
c.mu.Unlock()
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-c.closeCh:
if msg := c.stderr.String(); msg != "" {
return nil, fmt.Errorf("mcp: connection closed (%s)", msg)
}
return nil, fmt.Errorf("mcp: connection closed")
case resp := <-ch:
if resp.Error != nil {
return nil, resp.Error
}
return resp.Result, nil
}
}
func (c *stdioMCPClient) initialize(ctx context.Context) error {
_, err := c.call(ctx, "initialize", map[string]any{
"protocolVersion": "2024-11-05",
"capabilities": map[string]any{},
"clientInfo": map[string]any{"name": "norma", "version": "0.2"},
})
if err != nil {
return err
}
return c.notify("notifications/initialized", map[string]any{})
}
func (c *stdioMCPClient) Tools(ctx context.Context) ([]actool.CoreTool, error) {
raw, err := c.call(ctx, "tools/list", map[string]any{})
if err != nil {
return nil, err
}
var res struct {
Tools []stdioRemoteTool `json:"tools"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return nil, err
}
out := make([]actool.CoreTool, 0, len(res.Tools))
for _, rt := range res.Tools {
out = append(out, c.wrap(rt))
}
return out, nil
}
func (c *stdioMCPClient) wrap(rt stdioRemoteTool) actool.CoreTool {
schema := rt.InputSchema
if schema == nil {
schema = map[string]any{"type": "object"}
}
full := mcp.ToolName(c.server, rt.Name)
return actool.Build(actool.Spec{
Name: full,
Description: rt.Description,
Schema: schema,
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.AskUser("call MCP tool " + full + "?")
},
Run: func(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
var args any
if len(in) > 0 {
_ = json.Unmarshal(in, &args)
}
raw, err := c.call(ctx, "tools/call", map[string]any{"name": rt.Name, "arguments": args})
if err != nil {
return actool.Errorf("Error: " + err.Error()), nil
}
var res struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return actool.Errorf("Error: bad MCP response: " + err.Error()), nil
}
var text string
for _, blk := range res.Content {
text += blk.Text
}
return actool.Result{Content: []llm.ContentBlock{llm.TextBlock(actool.Capture(tc, text))}, IsError: res.IsError}, nil
},
})
}
func (c *stdioMCPClient) Close() error {
c.closeOnce.Do(func() {
if c.stdin != nil {
_ = c.stdin.Close()
}
if c.cmd != nil && c.cmd.Process != nil {
_ = c.cmd.Process.Kill()
_ = c.cmd.Wait()
}
})
return nil
}
+159 -12
View File
@@ -69,9 +69,12 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
s.toolListLLMProfiles(),
s.toolSpawnTask(),
s.toolPauseTask(),
s.toolResumeTask(),
s.toolGetTaskGraph(),
s.toolListTaskFindings(),
s.toolAddHint(),
s.toolSetTaskGoals(),
s.toolAddTaskIntent(),
s.toolGetWorkerTrace(),
s.toolListWorkerTraces(),
s.toolSearchWorkerTraces(),
@@ -147,6 +150,20 @@ func wrTool(name, desc string, schema map[string]any, run func(context.Context,
// delegateToTask resolves the `task_id` in the input, builds a ToolSet bound to
// that task's store, strips task_id, and calls the chosen per-task tool — so the
// cross-task read reuses the exact in-task logic against another task.
func (s *Server) lookupTask(raw string) (*Task, bool) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return nil, false
}
if t, ok := s.m.Task(trimmed); ok {
return t, true
}
if id, ok := canonicalTaskID(trimmed); ok {
return s.m.Task(id)
}
return nil, false
}
func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick func(*agent.ToolSet) actool.CoreTool) (actool.Result, error) {
var head struct {
TaskID string `json:"task_id"`
@@ -155,20 +172,31 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu
if strings.TrimSpace(head.TaskID) == "" {
return actool.Errorf("task_id 为必填"), nil
}
t, ok := s.m.Task(head.TaskID)
t, ok := s.lookupTask(head.TaskID)
if !ok {
return actool.Errorf("task 不存在: " + head.TaskID), nil
}
if s.engine != nil {
if !s.engine.beginTaskOperation(t.ID) {
return actool.Errorf("任务正在删除,无法操作: " + t.ID), nil
}
defer s.engine.decInflight(t.ID)
}
var m map[string]json.RawMessage
_ = json.Unmarshal(in, &m)
delete(m, "task_id")
inner, _ := json.Marshal(m)
tsx := agent.NewToolSet(t.Store, "orchestrator")
if taskIDInt, err := strconv.ParseInt(t.ID, 10, 64); err == nil && taskIDInt > 0 {
tsx.SetTaskID(taskIDInt)
}
if s.m.Assets() != nil {
tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies())
}
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_task_goals / add_task_intent → 把已完成/暂停的任务拉回 running
tsx.SetNotifyGoal(t.NotifyGoal) // set_task_goals → 记一条「人新增了 N 个目标:…」触发并唤醒 planner
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
return pick(tsx).Call(ctx, inner, nil)
}
@@ -379,6 +407,39 @@ func (s *Server) toolPauseTask() actool.CoreTool {
})
}
func (s *Server) toolResumeTask() actool.CoreTool {
return wrTool("resume_task",
"恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务继续运行(保留已有探索图、发现与 frontier,不新建重复任务)。当用户要求继续/重开已有任务时,优先使用本工具(或 set_task_goals / add_task_intent),不要用 spawn_task 另起重复任务。",
objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id;在任务内主 Agent 对话中可省略(默认当前任务)")}),
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
TaskID string `json:"task_id"`
}
_ = json.Unmarshal(in, &a)
rawID := strings.TrimSpace(a.TaskID)
if info := agent.RunInfoFrom(ctx); info.TaskID > 0 {
curID := strconv.FormatInt(info.TaskID, 10)
if rawID == "" {
rawID = curID
} else if canon, ok := canonicalTaskID(rawID); !ok || canon != curID {
return actool.Errorf(fmt.Sprintf("当前在任务 #%s 上下文中,只能恢复当前任务", curID)), nil
}
}
if rawID == "" {
return actool.Errorf("task_id 为必填"), nil
}
t, ok := s.lookupTask(rawID)
if !ok {
return actool.Errorf("task 不存在: " + rawID), nil
}
res, err := s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
if err != nil {
return actool.Errorf(err.Error()), nil
}
return jsonResult(map[string]any{"task_id": t.ID, "status": res.Status, "queued": res.Queued})
})
}
func (s *Server) toolGetTaskGraph() actool.CoreTool {
return roTool("get_task_graph", "读指定任务的探索图总览(同 graph_overview:资产计数/frontier/发现/覆盖等),用 task_id 指定任务。",
objSchema(map[string]any{"task_id": strParam("任务 id")}, "task_id"),
@@ -410,6 +471,38 @@ func (s *Server) toolAddHint() actool.CoreTool {
})
}
func (s *Server) toolSetTaskGoals() actool.CoreTool {
return wrTool("set_task_goals",
"给指定任务新增探索目标(goal),写入任务图并自动把已完成/暂停的任务拉回运行态继续规划执行(保留已有图谱与发现,无需另起新任务)。\n"+
"★优先批量:多个目标放进 goals 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 goals 直接给顶层 text。",
objSchema(map[string]any{
"task_id": strParam("任务 id"),
"goals": map[string]any{"type": "array", "description": "【优先用这个】要新增的目标数组,按顺序处理。每个元素:text(必填,一个独立可验证的最终目标)+ vulnclass(可选)。", "items": objSchema(map[string]any{"text": strParam("一个独立可验证的最终目标"), "vulnclass": strParam("可选:对应漏洞类,如 SQLi/IDOR")}, "text")},
"text": strParam("[单条] 一个独立可验证的最终目标"),
"vulnclass": strParam("[单条] 对应漏洞类(若明确),如 SQLi/IDOR;业务逻辑目标可留空"),
}, "task_id"),
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
return s.delegateToTask(ctx, in, (*agent.ToolSet).SetGoalsTool)
})
}
func (s *Server) toolAddTaskIntent() actool.CoreTool {
return wrTool("add_task_intent",
"给指定任务直接下发探索意图(intent)写入 frontier,并自动把已完成/暂停的任务拉回运行态让 worker 领取执行(保留已有图谱与发现,无需另起新任务)。\n"+
"★优先批量:多个方向放进 intents 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 intents 直接给顶层 summary。",
objSchema(map[string]any{
"task_id": strParam("任务 id"),
"intents": map[string]any{"type": "array", "description": "【优先用这个】要新增的探索方向数组,每个元素字段同顶层(summary/asset_ids/parent_ids/priority)。", "items": objSchema(map[string]any{"summary": strParam("探索方向摘要"), "asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "priority": map[string]any{"type": "integer"}}, "summary")},
"summary": strParam("[单条] 一句话描述这个探索方向:做什么+为什么"),
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "目标资产 id(可选,0/1/多个)"},
"parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "上游锚点 fact/finding 节点 id(可选,0/1/多个;顶层全新方向请留空)"},
"priority": map[string]any{"type": "integer", "description": "优先级 0-10,默认 5;直投紧急意图建议 8-10"},
}, "task_id"),
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
return s.delegateToTask(ctx, in, (*agent.ToolSet).AddIntentTool)
})
}
func (s *Server) toolGetWorkerTrace() actool.CoreTool {
return roTool("get_task_worker_trace",
"看指定任务里某个 work(意图)的执行过程:get_task_worker_trace(task_id, intent_id) 看步骤摘要;再带 step_ids=[...] 取那几步完整内容(一次最多 5 个,多传只返回前 5 个)。",
@@ -521,17 +614,24 @@ func (s *Server) deriveTaskStatus(t *Task) string {
// orchestrationToolSeeds seeds the cross-task tools into the tools table so they
// are bindable per-agent (default: bound to nobody — opt-in for orchestration
// agents). First-insert only, like the traffic seeds.
func defaultOrchestrationToolBindings(name string) json.RawMessage {
switch {
case name == "resume_task":
return json.RawMessage(`["auto","mainagent"]`)
case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records" || name == "suggest_finding_merge":
return json.RawMessage(`["reporter"]`)
default:
return json.RawMessage(`["auto"]`)
}
}
func (s *Server) seedOrchestrationTools() {
// task-op + platform tools default-bind to the built-in Auto agent (它天生用来
// 操作平台)。SeedTool 首插入生效;老库已 seed 的行由 seedAutoDefaultBindings 补绑。
autoAgents, _ := json.Marshal([]string{"auto"})
for _, t := range s.orchestrationTools() {
schema, _ := json.Marshal(t.InputSchema())
bindings := autoAgents
if t.Name() == "bind_finding_traffic" || strings.Contains(t.Name(), "finding_case") || t.Name() == "search_finding_duplicates" || t.Name() == "get_finding_record" || t.Name() == "merge_finding_records" || t.Name() == "suggest_finding_merge" {
bindings = json.RawMessage(`["reporter"]`)
}
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, bindings)
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name()))
}
for _, t := range s.platformTools() {
schema, _ := json.Marshal(t.InputSchema())
@@ -539,6 +639,7 @@ func (s *Server) seedOrchestrationTools() {
}
s.refreshBuiltinToolSchemas()
s.seedAutoDefaultBindings()
s.seedTaskReopenBindings()
s.seedPlannerDefaultBindings()
s.seedPlannerListAssetsBinding()
s.seedCompanyScopeRebind()
@@ -547,13 +648,14 @@ func (s *Server) seedOrchestrationTools() {
s.seedAutoReportFindingBinding()
s.unbindGoalMetDefault()
s.reseedGoalsPrompt() // goals 提示词加入「抽操作约束」步 → 旧库追加一版新默认(一次性)
s.reseedMainAgentPrompt() // mainagent 提示词加入「目标达成后 add_intent 反问是否建目标」(一次性)
s.reseedAutoPrompt() // auto 提示词加入 resume_task/set_task_goals/add_task_intent 与原地继续原则(一次性)
s.reseedMainAgentPrompt() // mainagent 提示词加入 resume_task 引导(一次性)
s.reseedPlannerPrompt() // planner 提示词:重写「0 意图」正当理由 + 加量化验收核对(一次性)
s.reseedWorkerPrompt() // worker 提示词:加否定结论证据门槛(一次性)
s.seedReporterAgent() // 预置「报告撰写」agent + 工具绑定 + finding 触发器(一次性)
s.upgradeReporterTriggerMessage() // 老库补迁移:让 reporter 回传 evidence_version(一次性)
s.migrateReporterWorkflow() // 修复旧库残留的 reproduction 工具/提示词绑定
if s.m.pg.GetBool(settingBrowserScreenshot, defaultBrowserScreenshot) {
if s.m.pg.GetBool(settingBrowserScreenshot, false) {
// Re-apply the opt-in after startup seeding so an existing database gets
// both reporter visibility and the repaired Playwright launch arguments.
if err := s.setReporterBrowserScreenshotVisibility(true); err != nil {
@@ -629,7 +731,7 @@ func (s *Server) migrateReporterWorkflow() {
// reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag.
// Bump the flag whenever these tools' schemas/descriptions change in code.
func (s *Server) refreshBuiltinToolSchemas() {
const flag = "tool_schema_refresh_v8_finding_case_tools"
const flag = "tool_schema_refresh_v9_task_reopen_tools"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -714,7 +816,7 @@ func (s *Server) reseedGoalsPrompt() {
// 保留在历史里,用户若自定义过可从版本记录找回。settings flag 守卫 → 只做一次。全新库无需处理
// (SeedPromptIfEmpty 已 seed 最新默认)。与 reseedGoalsPrompt 完全同构。
func (s *Server) reseedMainAgentPrompt() {
const flag = "mainagent_prompt_goalless_intent_v1"
const flag = "mainagent_prompt_task_reopen_v2"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -738,6 +840,32 @@ func (s *Server) reseedMainAgentPrompt() {
log.Printf("[prompts] mainagent 提示词已追加新默认版本(加入目标达成后反问建目标,一次性)")
}
// reseedAutoPrompt 把 auto 提示词刷成【当前代码默认】——加入 resume_task /
// set_task_goals / add_task_intent 以及「原地继续优先于新建任务」原则。
func (s *Server) reseedAutoPrompt() {
const flag = "auto_prompt_task_reopen_v1"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
defer func() { _ = s.m.pg.SetSetting(flag, "true") }()
a, err := s.m.pg.GetAgentByKey("auto")
if err != nil || a == nil {
return
}
tmpl := agent.BuiltinPromptSeeds()["auto"]
if tmpl == "" {
return
}
if cur, err := s.m.pg.CurrentPrompt(a.ID); err == nil && cur == tmpl {
return
}
if _, err := s.m.pg.ResetPromptToDefault(a.ID, tmpl); err != nil {
log.Printf("[prompts] auto 提示词重刷为新默认失败: %v", err)
return
}
log.Printf("[prompts] auto 提示词已追加新默认版本(加入 resume_task/set_task_goals/add_task_intent,一次性)")
}
// reseedPlannerPrompt 把 planner 提示词刷成【当前代码默认】——默认正文做了精简重构,并把「克制」降级为
// 仅去重、新增「深度优先于覆盖度」「硬底线:目标未达成且无在跑意图必须产出」、给否定结论复核加上界。
// 每次默认有实质变更就 bump 下面的 flag(当前 v2)让存量旧库再刷一次。SeedPromptIfEmpty 首插入only,旧库已有版本收不到,故用版本管理
@@ -1033,3 +1161,22 @@ func (s *Server) seedAutoDefaultBindings() {
}
_ = s.m.pg.SetSetting(flag, "true")
}
// seedTaskReopenBindings adds the task reopen/steering orchestration tools to
// existing DBs ONCE (guarded by a settings flag), without re-adding unrelated
// tools a user may have deliberately unbound.
func (s *Server) seedTaskReopenBindings() {
const flag = "task_reopen_bindings_v1"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
if err := s.m.pg.AddAgentToToolBinding("auto", []string{"resume_task", "set_task_goals", "add_task_intent"}); err != nil {
log.Printf("[auto] 任务重开/操舵工具默认绑定失败: %v", err)
return
}
if err := s.m.pg.AddAgentToToolBinding("mainagent", []string{"resume_task"}); err != nil {
log.Printf("[mainagent] resume_task 默认绑定失败: %v", err)
return
}
_ = s.m.pg.SetSetting(flag, "true")
}
+23 -6
View File
@@ -228,7 +228,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
if err != nil || t == "" {
return "", false
}
if key == "reporter" && m.pg.GetBool(settingBrowserScreenshot, defaultBrowserScreenshot) {
if key == "reporter" && m.pg.GetBool(settingBrowserScreenshot, false) {
t += `
【报告步骤截图已开启】
@@ -267,7 +267,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
}
return a.TaskTimeoutWrapupMaxTurns, true
}
wireAgentAugment(m.pg, s.skillDir, m.dir, s.hostTools) // 可见 skills/MCP + 流量/编排 host 工具装配进 agent 工具集
wireAgentAugment(m.pg, s.skillDir, s.hostTools) // 可见 skills/MCP + 流量/编排 host 工具装配进 agent 工具集
domainReg := buildDomainReg(m.Assets())
wireTools(m.pg, domainReg) // 内置工具表:按 agent 过滤 + 覆盖描述/schema + 注入默认值
seedPrompts(m.pg) // 内置 agent 默认提示词正文播种进 agent_prompts(仅空时)
@@ -910,6 +910,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // 约束管理:修改约束
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // 约束管理:删除约束
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
mux.HandleFunc("POST /api/tasks/{id}/resume", s.resumeTask)
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
@@ -1389,6 +1390,22 @@ func (s *Server) control(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, result)
}
// resumeTask resumes a paused task or reopens a terminal task (done/failed/timeout)
// in place when it still has open goals or open intents.
func (s *Server) resumeTask(w http.ResponseWriter, r *http.Request) {
t, ok := s.lookupTask(r.PathValue("id"))
if !ok {
writeErr(w, 404, "task not found")
return
}
result, err := s.resumeOrReopenTask(t, agent.AbortPausedByUser)
if err != nil {
writeErr(w, 409, err.Error())
return
}
writeJSON(w, 200, result)
}
// controlIntent pauses, resumes, or cancels one local worker intent. A running
// worker is always stopped before state mutation/cleanup, preventing tool output
// that arrives after the user action from recreating deleted blackboard records.
@@ -3827,11 +3844,11 @@ func (s *Server) settingsPayload() map[string]any {
}
return map[string]any{
"traffic_capture": s.m.TrafficEnabled(),
"browser_screenshot_enabled": s.m.pg.GetBool(settingBrowserScreenshot, defaultBrowserScreenshot),
"browser_screenshot_timestamp_enabled": s.m.pg.GetBool(settingScreenshotTimestamp, defaultScreenshotTimestamp),
"browser_screenshot_enabled": s.m.pg.GetBool(settingBrowserScreenshot, false),
"browser_screenshot_timestamp_enabled": s.m.pg.GetBool(settingScreenshotTimestamp, false),
"opsec_enabled": s.m.pg.GetBool(settingOpsecEnabled, false),
"agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, defaultAgentTrafficBinding),
"task_intelligence_enabled": s.m.pg.GetBool(db.SettingTaskIntelligence, db.DefaultTaskIntelligence),
"agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, false),
"task_intelligence_enabled": s.m.pg.GetBool(db.SettingTaskIntelligence, false),
db.SettingTaskAutoTitle: s.m.pg.GetBool(db.SettingTaskAutoTitle, false),
db.SettingChatAutoTitle: s.m.pg.GetBool(db.SettingChatAutoTitle, false),
db.SettingCredentialAgent: s.m.pg.GetBool(db.SettingCredentialAgent, false),
+15 -2
View File
@@ -840,9 +840,22 @@ func (s *Server) pgResetTool(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"ok": true})
return
}
// orchestration/platform tools (auto agent) — default-bind to "auto".
// orchestration tools use per-tool default bindings (auto / auto+mainagent / reporter).
for _, t := range s.orchestrationTools() {
if t.Name() != key {
continue
}
schema, _ := json.Marshal(t.InputSchema())
if err := pg.UpsertToolForce(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name())); err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"ok": true})
return
}
// platform tools (auto agent) — default-bind to "auto".
autoAgents, _ := json.Marshal([]string{"auto"})
for _, t := range append(s.orchestrationTools(), s.platformTools()...) {
for _, t := range s.platformTools() {
if t.Name() != key {
continue
}
+82
View File
@@ -193,6 +193,88 @@ func (s *Server) applyTaskControlWithCause(t *Task, action string, pauseCause er
return out, nil
}
// resumeOrReopenTask resumes a paused task or reopens a terminal
// (done/failed/timeout) task in place when it still has open goals or open
// intents to execute. Unlike applyTaskControl("resume"), which stays strictly
// paused-only for schedule/proxy/batch control callers, this is the explicit
// operator/agent reopen path (POST /api/tasks/{id}/resume and resume_task).
func (s *Server) resumeOrReopenTask(t *Task, cause error) (taskControlResult, error) {
if t == nil {
return taskControlResult{}, fmt.Errorf("task not found")
}
out := taskControlResult{ID: t.ID}
lifecycle := t.lifecycleSnapshot()
if !isTerminalStatus(lifecycle.Status) {
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
return s.applyTaskControlWithCause(t, "resume", cause)
}
if lifecycle.Queued {
return out, fmt.Errorf("任务当前已在排队等待运行,无需恢复")
}
if s.engine.Started(t.ID) {
return out, fmt.Errorf("任务当前正在运行,无需恢复")
}
mode := s.resumeAdmissionMode(t)
queued, err := s.admitTask(t, mode)
if err != nil {
return out, err
}
out.Queued = queued
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
return out, nil
}
if !s.engine.beginTaskOperation(t.ID) {
return out, fmt.Errorf("任务正在删除,无法恢复")
}
defer s.engine.decInflight(t.ID)
current, exists := s.m.Task(t.ID)
if !exists || current != t || s.engine.IsDeleting(t.ID) {
return out, fmt.Errorf("任务正在删除,无法恢复")
}
lifecycle = t.lifecycleSnapshot()
if !isTerminalStatus(lifecycle.Status) {
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
return s.applyTaskControlWithCause(t, "resume", cause)
}
out.Queued = lifecycle.Queued
out.Status = s.deriveTaskStatus(t)
return out, nil
}
hasOpenGoal, err := t.Store.HasOpenGoal()
if err != nil {
return out, err
}
hasActiveIntent, err := t.Store.HasActiveIntent()
if err != nil {
return out, err
}
mode := "resume"
if !hasOpenGoal && !hasActiveIntent {
goals, gErr := t.Store.ListByKind(db.KindGoal, 1)
if gErr == nil && len(goals) == 0 && lifecycle.FirstRunAt == 0 {
mode = "bootstrap"
} else {
return out, fmt.Errorf("任务所有目标均已达成且没有待执行(open)的意图,无法直接恢复;请先通过 set_goals/set_task_goals 新增目标,或通过 add_intent/add_task_intent 下发新意图(系统会自动将任务拉回运行态)")
}
}
queued, err := s.admitTask(t, mode)
if err != nil {
return out, err
}
out.Queued = queued
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
summary := "任务已重新打开,继续执行剩余探索任务"
if queued {
summary = "任务已重新打开并进入排队,等待运行槽位"
}
s.engine.emitActivity(t, db.Activity{Worker: "system", Kind: "text", Summary: summary})
log.Printf("[task] #%s 已重新打开继续运行 (from=%s status=%s)", t.ID, lifecycle.Status, out.Status)
return out, nil
}
// intentSummaryOf 取意图 payload 里的 summary,供删除通知在意图节点消失(真删除)前留档。
func intentSummaryOf(n *db.Node) string {
if n == nil {
+438
View File
@@ -0,0 +1,438 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
actool "github.com/Autumn-27/norma/tool"
)
func toolResultText(res actool.Result) string {
var parts []string
for _, b := range res.Content {
if b.Text != "" {
parts = append(parts, b.Text)
}
}
return strings.Join(parts, "\n")
}
func TestResumeTaskToolReopensDoneTaskWithOpenIntents(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
task, err := m.CreateTask("reopen done task", "finish open intents", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
goalID, err := task.Store.AddGoal(map[string]any{"text": "initial goal"}, "system")
if err != nil {
t.Fatal(err)
}
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
t.Fatal(err)
}
intentID, err := task.Store.AddIntent(map[string]any{"summary": "test /admin endpoint"}, 8, nil, "planner")
if err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
t.Fatal(err)
}
s := newAdmissionTestServer(m, nil)
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("resume_task failed: %s", toolResultText(res))
}
var out struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Queued bool `json:"queued"`
}
if err := json.Unmarshal([]byte(toolResultText(res)), &out); err != nil {
t.Fatalf("unmarshal result %q: %v", toolResultText(res), err)
}
if out.TaskID != task.ID || out.Status != "running" || out.Queued {
t.Fatalf("resume_task result = %+v, want task_id=%s status=running queued=false", out, task.ID)
}
if got := m.TaskStatus(task.ID); got != "running" {
t.Fatalf("in-memory task status = %q, want running", got)
}
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
if err != nil || stored == nil {
t.Fatalf("GetTask: %v", err)
}
if stored.Status != "running" || stored.Paused || stored.CompletedAt != nil {
t.Fatalf("stored task = %+v, want status=running paused=false completed_at=nil", stored)
}
// Existing open intent must still be present in place.
node, err := task.Store.GetNode(intentID)
if err != nil || node == nil || node.State != "open" {
t.Fatalf("open intent after reopen = %+v err=%v, want state=open", node, err)
}
}
func TestResumeTaskToolRefusesDoneTaskWithNoOpenWork(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
task, err := m.CreateTask("done no work", "all goals met", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
goalID, err := task.Store.AddGoal(map[string]any{"text": "finished goal"}, "system")
if err != nil {
t.Fatal(err)
}
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
t.Fatal(err)
}
s := newAdmissionTestServer(m, nil)
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError {
t.Fatalf("expected error for done task with no open goals/intents, got: %s", toolResultText(res))
}
if got := m.TaskStatus(task.ID); got != "done" {
t.Fatalf("status changed to %q on refused reopen, want done", got)
}
}
func TestResumeTaskToolInMainAgentContextDefaultsAndScopesTaskID(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
task1, err := m.CreateTask("task1", "goal1", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task1.ID, DeleteTaskOptions{}) }()
task2, err := m.CreateTask("task2", "goal2", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task2.ID, DeleteTaskOptions{}) }()
if _, err := task1.Store.AddIntent(map[string]any{"summary": "open work 1"}, 5, nil, "planner"); err != nil {
t.Fatal(err)
}
if _, err := task2.Store.AddIntent(map[string]any{"summary": "open work 2"}, 5, nil, "planner"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task1.ID, "done"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task2.ID, "done"); err != nil {
t.Fatal(err)
}
s := newAdmissionTestServer(m, nil)
ctx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: mustTaskID(t, task1.ID)})
// Cross-task call from task1 context must be refused.
crossIn, _ := json.Marshal(map[string]any{"task_id": task2.ID})
crossRes, err := s.toolResumeTask().Call(ctx, crossIn, nil)
if err != nil {
t.Fatal(err)
}
if !crossRes.IsError {
t.Fatalf("expected cross-task resume refusal, got: %s", toolResultText(crossRes))
}
if m.TaskStatus(task2.ID) != "done" {
t.Fatalf("task2 status = %q, want done", m.TaskStatus(task2.ID))
}
// Empty task_id in task1 context defaults to task1 and reopens it.
selfRes, err := s.toolResumeTask().Call(ctx, json.RawMessage(`{}`), nil)
if err != nil {
t.Fatal(err)
}
if selfRes.IsError {
t.Fatalf("in-task resume_task failed: %s", toolResultText(selfRes))
}
if m.TaskStatus(task1.ID) != "running" {
t.Fatalf("task1 status = %q, want running", m.TaskStatus(task1.ID))
}
}
func TestSetTaskGoalsAndAddTaskIntentReviveDoneAndPausedTasks(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
s := newAdmissionTestServer(m, nil)
// 1. set_task_goals on a done task (no open goals/intents) writes an open goal and revives it.
doneTask, err := m.CreateTask("done for set_task_goals", "old goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(doneTask.ID, DeleteTaskOptions{}) }()
gID, err := doneTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
if err != nil {
t.Fatal(err)
}
if err := doneTask.Store.SetNodeState(gID, "met"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(doneTask.ID, "done"); err != nil {
t.Fatal(err)
}
inGoals, _ := json.Marshal(map[string]any{
"task_id": doneTask.ID,
"text": "verify SSRF on /api/fetch",
})
res, err := s.toolSetTaskGoals().Call(context.Background(), inGoals, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("set_task_goals failed: %s", toolResultText(res))
}
if got := m.TaskStatus(doneTask.ID); got != "running" {
t.Fatalf("doneTask status after set_task_goals = %q, want running", got)
}
hasOpenGoal, err := doneTask.Store.HasOpenGoal()
if err != nil || !hasOpenGoal {
t.Fatalf("doneTask HasOpenGoal = %v err=%v, want true", hasOpenGoal, err)
}
// 2. set_task_goals on a paused task clears pause and revives it.
if _, err := s.applyTaskControl(doneTask, "pause"); err != nil {
t.Fatal(err)
}
if !doneTask.lifecycleSnapshot().Paused {
t.Fatal("expected task to be paused")
}
inGoals2, _ := json.Marshal(map[string]any{
"task_id": doneTask.ID,
"goals": []map[string]any{{"text": "check IDOR on /api/users/{id}", "vulnclass": "IDOR"}},
})
res, err = s.toolSetTaskGoals().Call(context.Background(), inGoals2, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("set_task_goals on paused task failed: %s", toolResultText(res))
}
if doneTask.lifecycleSnapshot().Paused || s.engine.IsPaused(doneTask.ID) {
t.Fatalf("task still paused after set_task_goals: lifecycle=%+v enginePaused=%v", doneTask.lifecycleSnapshot(), s.engine.IsPaused(doneTask.ID))
}
// 3. add_task_intent on a done task creates an open intent and revives it.
intentTask, err := m.CreateTask("done for add_task_intent", "old goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(intentTask.ID, DeleteTaskOptions{}) }()
gID2, err := intentTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
if err != nil {
t.Fatal(err)
}
if err := intentTask.Store.SetNodeState(gID2, "met"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(intentTask.ID, "done"); err != nil {
t.Fatal(err)
}
inIntent, _ := json.Marshal(map[string]any{
"task_id": intentTask.ID,
"summary": "probe /internal/metrics directly",
"priority": 9,
})
res, err = s.toolAddTaskIntent().Call(context.Background(), inIntent, nil)
if err != nil {
t.Fatal(err)
}
if res.IsError {
t.Fatalf("add_task_intent failed: %s", toolResultText(res))
}
if got := m.TaskStatus(intentTask.ID); got != "running" {
t.Fatalf("intentTask status after add_task_intent = %q, want running", got)
}
hasActive, err := intentTask.Store.HasActiveIntent()
if err != nil || !hasActive {
t.Fatalf("intentTask HasActiveIntent = %v err=%v, want true", hasActive, err)
}
}
func TestHTTPResumeTaskEndpoint(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
td := t.TempDir()
s := New(ctx, m, td, td, td)
planner, worker := new(agent.Planner), new(agent.Worker)
s.engine.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
return planner, worker
})
h := s.Handler()
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
postResume := func(id string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/api/tasks/"+id+"/resume", nil)
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// Missing task → 404.
if rec := postResume("999999999"); rec.Code != http.StatusNotFound {
t.Fatalf("missing task status = %d body=%s, want 404", rec.Code, rec.Body.String())
}
task, err := m.CreateTask("http resume", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
goalID, err := task.Store.AddGoal(map[string]any{"text": "g"}, "system")
if err != nil {
t.Fatal(err)
}
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
t.Fatal(err)
}
// Done task with no open goals/intents → 409.
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
t.Fatalf("done task with no work status = %d body=%s, want 409", rec.Code, rec.Body.String())
}
// Add an open intent → POST /api/tasks/{id}/resume reopens to 200 running.
if _, err := task.Store.AddIntent(map[string]any{"summary": "continue open work"}, 7, nil, "planner"); err != nil {
t.Fatal(err)
}
rec := postResume(task.ID)
if rec.Code != http.StatusOK {
t.Fatalf("reopen done task status = %d body=%s, want 200", rec.Code, rec.Body.String())
}
var body taskControlResult
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.ID != task.ID || body.Status != "running" || body.Paused {
t.Fatalf("resume body = %+v, want id=%s status=running paused=false", body, task.ID)
}
// Already running → 409.
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
t.Fatalf("already running status = %d body=%s, want 409", rec.Code, rec.Body.String())
}
// Pause then resume → 200 running.
if _, err := s.applyTaskControl(task, "pause"); err != nil {
t.Fatal(err)
}
if rec := postResume(task.ID); rec.Code != http.StatusOK {
t.Fatalf("resume paused task status = %d body=%s, want 200", rec.Code, rec.Body.String())
}
}
func TestAutoAndMainAgentToolResolutionIncludesReopenTools(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Skipf("postgres unavailable (%v) - skipping", err)
}
defer m.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
td := t.TempDir()
s := New(ctx, m, td, td, td)
t.Cleanup(func() { agent.ToolResolve = nil })
// Verify auto gets resume_task, set_task_goals, add_task_intent via ToolResolve.
hostTools, _ := s.hostTools()
autoTools := names(agent.ToolResolve(context.Background(), "auto", append(actool.DefaultTools(), hostTools...)))
for _, want := range []string{"resume_task", "set_task_goals", "add_task_intent", "pause_task", "add_task_hint"} {
if _, ok := autoTools[want]; !ok {
t.Errorf("auto missing bound tool %q", want)
}
}
// Verify mainagent gets resume_task alongside set_goals and add_intent.
ts := agent.NewToolSet(nil, "human")
mainBase := append(ts.MainAgentTools(), hostTools...)
mainTools := names(agent.ToolResolve(context.Background(), "mainagent", mainBase))
for _, want := range []string{"resume_task", "set_goals", "add_intent", "add_hint"} {
if _, ok := mainTools[want]; !ok {
t.Errorf("mainagent missing bound tool %q", want)
}
}
// Verify cross-task-only tools are NOT leaked into mainagent.
for _, unwanted := range []string{"set_task_goals", "add_task_intent"} {
if _, ok := mainTools[unwanted]; ok {
t.Errorf("mainagent should not receive cross-task tool %q", unwanted)
}
}
// Verify MCP resume_task can also reopen a done task with open intents.
task, err := m.CreateTask("mcp reopen", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
if _, err := task.Store.AddIntent(map[string]any{"summary": "remaining intent"}, 6, nil, "planner"); err != nil {
t.Fatal(err)
}
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
t.Fatal(err)
}
tok := &db.APIToken{ID: 1, Name: "test", Scopes: []string{db.APIScopeTaskControl}}
mcpIn, _ := json.Marshal(map[string]any{"task_id": task.ID})
mcpRes, err := s.mcpControlTask(tok, mcpIn, "resume")
if err != nil {
t.Fatal(err)
}
if mcpRes.IsError || !strings.Contains(toolResultText(mcpRes), `"running"`) {
t.Fatalf("mcp resume_task on done task = %+v, want running", mcpRes)
}
}
+4 -9
View File
@@ -255,7 +255,7 @@ func (s *Server) wsPreview(w http.ResponseWriter, r *http.Request) {
writeErr(w, 415, "仅支持图片预览")
return
}
if s.m.pg.GetBool(settingScreenshotTimestamp, defaultScreenshotTimestamp) {
if s.m.pg.GetBool(settingScreenshotTimestamp, false) {
rawRel := filepath.ToSlash(strings.TrimPrefix(strings.TrimSpace(rawPath), "/"))
rel := filepath.ToSlash(s.wsRel(abs))
if strings.HasPrefix(rawRel, "findings/screenshots/") || strings.HasPrefix(rel, "findings/screenshots/") || strings.Contains(rel, "/findings/screenshots/") {
@@ -280,14 +280,9 @@ func (s *Server) findSessionPreview(rawPath string) (string, bool) {
if rel == "." || !strings.HasPrefix(rel, prefix) || strings.Contains(rel, ".."+string(os.PathSeparator)) {
return "", false
}
root := filepath.Clean(s.m.dir)
var matches []string
for _, sub := range []string{"sessions", "tasks"} {
if found, err := filepath.Glob(filepath.Join(root, sub, "*", filepath.FromSlash(rel))); err == nil {
matches = append(matches, found...)
}
}
if len(matches) == 0 {
base := filepath.Join(filepath.Clean(s.m.dir), "sessions")
matches, err := filepath.Glob(filepath.Join(base, "*", filepath.FromSlash(rel)))
if err != nil || len(matches) == 0 {
return "", false
}
var newest string
+8 -8
View File
@@ -40,17 +40,17 @@ export default function SystemSettingsPage() {
const [credentialAgent, setCredentialAgent] = React.useState(false);
const [credentialBinding, setCredentialBinding] = React.useState(false);
const [savingCredentials, setSavingCredentials] = React.useState(false);
const [intelligenceEnabled, setIntelligenceEnabled] = React.useState(true);
const [intelligenceEnabled, setIntelligenceEnabled] = React.useState(false);
const [taskAutoTitleEnabled, setTaskAutoTitleEnabled] = React.useState(false);
const [chatAutoTitleEnabled, setChatAutoTitleEnabled] = React.useState(false);
const [savingIntelligence, setSavingIntelligence] = React.useState(false);
const [trafficCapture, setTrafficCapture] = React.useState(false);
const [browserScreenshot, setBrowserScreenshot] = React.useState(true);
const [browserScreenshotTimestamp, setBrowserScreenshotTimestamp] = React.useState(true);
const [browserScreenshot, setBrowserScreenshot] = React.useState(false);
const [browserScreenshotTimestamp, setBrowserScreenshotTimestamp] = React.useState(false);
const [opsecEnabled, setOpsecEnabled] = React.useState(false);
const [settingQuery, setSettingQuery] = React.useState("");
const [activeCategory, setActiveCategory] = React.useState("system");
const [agentTrafficBinding, setAgentTrafficBinding] = React.useState(true);
const [agentTrafficBinding, setAgentTrafficBinding] = React.useState(false);
const [webSearch, setWebSearch] = React.useState(false);
const [backend, setBackend] = React.useState("ddgs");
const [braveKeySet, setBraveKeySet] = React.useState(false);
@@ -123,14 +123,14 @@ export default function SystemSettingsPage() {
const apply = React.useCallback((s: Settings) => {
setCredentialAgent(!!s.credential_agent_enabled);
setCredentialBinding(!!s.credential_traffic_binding);
setIntelligenceEnabled(s.task_intelligence_enabled !== false);
setIntelligenceEnabled(!!s.task_intelligence_enabled);
setTaskAutoTitleEnabled(!!s.task_auto_title_enabled);
setChatAutoTitleEnabled(!!s.chat_auto_title_enabled);
setTrafficCapture(!!s.traffic_capture);
setBrowserScreenshot(s.browser_screenshot_enabled !== false);
setBrowserScreenshotTimestamp(s.browser_screenshot_timestamp_enabled !== false);
setBrowserScreenshot(!!s.browser_screenshot_enabled);
setBrowserScreenshotTimestamp(!!s.browser_screenshot_timestamp_enabled);
setOpsecEnabled(!!s.opsec_enabled);
setAgentTrafficBinding(s.agent_traffic_binding !== false);
setAgentTrafficBinding(!!s.agent_traffic_binding);
setWebSearch(!!s.web_search_enabled);
setBackend(s.web_search_backend || "ddgs");
setBraveKeySet(!!s.brave_key_set);
+4 -4
View File
@@ -187,8 +187,8 @@ export const settingsMessages = {
"settings.captureOff": ["已关闭 · 不记录、不注入代理", "Disabled · No recording or proxy settings"],
"settings.trafficBinding": ["Agent 自动绑定流量", "Automatic Agent traffic binding"],
"settings.trafficBindingHelp": [
"默认开启。开启后,漏洞入库时触发的报告 Agent 会核对已有 HTTP 请求/响应,关联对应流量后再编写报告。",
"Enabled by default. When a finding is saved, the report Agent reviews existing HTTP requests and responses and links matching traffic before writing the report. ",
"默认关闭。开启后,漏洞入库时触发的报告 Agent 会核对已有 HTTP 请求/响应,关联对应流量后再编写报告。",
"Disabled by default. When a finding is saved, the report Agent reviews existing HTTP requests and responses and links matching traffic before writing the report. ",
],
"settings.trafficBindingCost": [
"查阅数据包及额外的工具调用会增加 Token 消耗。",
@@ -389,8 +389,8 @@ export const settingsMessages = {
],
"settings.autoRecord": ["Agent 自动记录", "Automatic Agent recording"],
"settings.autoRecordHelp": [
"默认开启。任务执行时上报凭据、重要线索和敏感数据,会增加任务 Agent 的提示与上报 Token。仅负责记录,不启动凭据整理。关闭后同时停用下方 Agent 与流量绑定,已有情报和整理结果仍可查看。",
"Enabled by default. Reporting credentials, leads and sensitive data uses additional Agent instruction and reporting tokens. This only records data; it does not start credential processing. Disabling it also disables the Agent and traffic binding below. Existing intelligence and processed results remain available.",
"默认关闭。任务执行时上报凭据、重要线索和敏感数据,会增加任务 Agent 的提示与上报 Token。仅负责记录,不启动凭据整理。关闭后同时停用下方 Agent 与流量绑定,已有情报和整理结果仍可查看。",
"Disabled by default. Reporting credentials, leads and sensitive data uses additional Agent instruction and reporting tokens. This only records data; it does not start credential processing. Disabling it also disables the Agent and traffic binding below. Existing intelligence and processed results remain available.",
],
"settings.autoRecordEnabled": ["任务情报自动记录已开启", "Automatic intelligence recording enabled"],
"settings.autoRecordDisabled": ["任务情报自动记录已关闭", "Automatic intelligence recording disabled"],
+2 -4
View File
@@ -3347,15 +3347,13 @@ export const tools: Tool[] = [
// ── Settings ─────────────────────────────────────────────────────────────────
export const settings: Settings = {
browser_screenshot_enabled: true,
browser_screenshot_timestamp_enabled: true,
task_intelligence_enabled: true,
task_intelligence_enabled: false,
credential_agent_enabled: false,
credential_traffic_binding: false,
task_auto_title_enabled: false,
chat_auto_title_enabled: false,
traffic_capture: true,
agent_traffic_binding: true,
agent_traffic_binding: false,
llm_record: false,
web_search_enabled: true,
web_search_backend: "ddgs",
+4 -4
View File
@@ -986,18 +986,18 @@ export interface TrafficHost {
// ---- App settings (runtime toggles) ----
export interface Settings {
traffic_capture: boolean;
/** 是否向可见 Agent 暴露浏览器 MCP 的截图工具。默认开启。 */
/** 是否向可见 Agent 暴露浏览器 MCP 的截图工具。默认关闭。 */
browser_screenshot_enabled?: boolean;
/** 是否在报告截图右上角显示截图保存时间。默认开启。 */
/** 是否在报告截图右上角显示截图保存时间。默认关闭。 */
browser_screenshot_timestamp_enabled?: boolean;
/** 是否向 Agent 注入统一 OPSEC 准则。默认关闭。 */
opsec_enabled?: boolean;
credential_agent_enabled: boolean;
credential_traffic_binding: boolean;
task_intelligence_enabled: boolean; // 默认开启;关闭不注入情报工具或提示
task_intelligence_enabled: boolean; // 默认关闭;关闭不注入情报工具或提示
task_auto_title_enabled: boolean; // Agent 创建任务时自动生成任务名称
chat_auto_title_enabled: boolean; // 对话首条消息后自动生成会话标题
agent_traffic_binding: boolean; // Agent 自动绑定流量证据,默认开启;不影响人工绑定
agent_traffic_binding: boolean; // Agent 自动绑定流量证据,默认关闭;不影响人工绑定
llm_record: boolean; // LLM 录制开关(默认关);关闭时不记录任何 LLM 调用
// Web search. brave_key_set / tavily_key_set reflect whether a key is stored
// (the values are never returned). On PUT, send the corresponding field to set/clear.