mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-06 21:11:50 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea49ba0a3a |
No files matched your search
+7
-7
@@ -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
@@ -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()
|
||||
|
||||
|
||||
+3
-3
@@ -127,12 +127,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
@@ -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) // 操作约束(若有)注入系统提示,框定探索边界
|
||||
|
||||
@@ -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
|
||||
|
||||
+6
-6
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
+201
-21
@@ -197,6 +197,64 @@ func (d *DB) ListPendingIntercepts() ([]InterceptPending, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListPendingInterceptsByTask returns unresolved approval requests for one task,
|
||||
// newest first.
|
||||
func (d *DB) ListPendingInterceptsByTask(taskID string) ([]InterceptPending, error) {
|
||||
rows, err := d.Query(`SELECT `+interceptPendingCols+` FROM intercept_pending WHERE status='pending' AND task_id=$1 ORDER BY created_at DESC`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []InterceptPending
|
||||
for rows.Next() {
|
||||
var p InterceptPending
|
||||
if err := scanInterceptPending(rows, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// InterceptPendingSummary is a lightweight snapshot of unresolved approval
|
||||
// requests without loading tool_input JSONB or historical rows.
|
||||
type InterceptPendingSummary struct {
|
||||
Count int `json:"count"`
|
||||
AgentNames []string `json:"agent_names,omitempty"`
|
||||
}
|
||||
|
||||
// CountPendingIntercepts returns the number of unresolved approval requests.
|
||||
func (d *DB) CountPendingIntercepts() (int, error) {
|
||||
var count int
|
||||
if err := d.QueryRow(`SELECT COUNT(*) FROM intercept_pending WHERE status='pending'`).Scan(&count); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// TaskPendingInterceptSummary returns the pending count and distinct agent names
|
||||
// awaiting approval for one task.
|
||||
func (d *DB) TaskPendingInterceptSummary(taskID string) (InterceptPendingSummary, error) {
|
||||
rows, err := d.Query(`SELECT agent_name, COUNT(*) FROM intercept_pending WHERE status='pending' AND task_id=$1 GROUP BY agent_name ORDER BY agent_name`, taskID)
|
||||
if err != nil {
|
||||
return InterceptPendingSummary{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := InterceptPendingSummary{AgentNames: []string{}}
|
||||
for rows.Next() {
|
||||
var agent string
|
||||
var n int
|
||||
if err := rows.Scan(&agent, &n); err != nil {
|
||||
return InterceptPendingSummary{}, err
|
||||
}
|
||||
out.Count += n
|
||||
if agent != "" {
|
||||
out.AgentNames = append(out.AgentNames, agent)
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetInterceptPending returns one pending record (nil if absent).
|
||||
func (d *DB) GetInterceptPending(id int64) (*InterceptPending, error) {
|
||||
var p InterceptPending
|
||||
@@ -243,10 +301,13 @@ const approvalRowColumns = `ip.id, ip.rule_id, ip.conversation_id, ip.task_id, i
|
||||
const approvalRowJoins = `
|
||||
FROM intercept_pending ip
|
||||
LEFT JOIN conversations c ON c.id = ip.conversation_id
|
||||
LEFT JOIN tasks t ON t.id::text = ip.task_id
|
||||
LEFT JOIN intercept_rules ir ON ir.id = ip.rule_id`
|
||||
|
||||
const approvalRowSearchJoins = approvalRowJoins + `
|
||||
LEFT JOIN tasks t ON t.id::text = ip.task_id`
|
||||
|
||||
const approvalRowSelect = `SELECT ` + approvalRowColumns + approvalRowJoins
|
||||
const approvalRowSearchSelect = `SELECT ` + approvalRowColumns + approvalRowSearchJoins
|
||||
const approvalRowSelectWithAudit = `SELECT ` + approvalRowColumns + `, ip.audit` + approvalRowJoins
|
||||
|
||||
func interceptSource(ruleID int64, reason string) string {
|
||||
@@ -299,14 +360,42 @@ type InterceptApprovalFilter struct {
|
||||
CreatedTo string // inclusive UTC calendar date, YYYY-MM-DD
|
||||
}
|
||||
|
||||
// ListAllInterceptsPage returns one 1-based page and the total matching count.
|
||||
func (d *DB) ListAllInterceptsPage(page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
|
||||
// InterceptApprovalPage is one 1-based page of approval history.
|
||||
// When TotalApproximate is true, Total is either a PostgreSQL table-size
|
||||
// estimate (unfiltered large table) or a lower bound (TotalCapped == true)
|
||||
// rather than an exact full-table count.
|
||||
type InterceptApprovalPage struct {
|
||||
Items []InterceptApprovalRow
|
||||
Total int
|
||||
TotalApproximate bool
|
||||
TotalCapped bool
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// interceptExactCountCap bounds exact COUNT(*) scans so large tables never
|
||||
// trigger unbounded full scans on every poll. Tests may override it.
|
||||
var interceptExactCountCap = 10000
|
||||
|
||||
// ListAllInterceptsPage returns one 1-based page and matching count metadata.
|
||||
func (d *DB) ListAllInterceptsPage(page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
|
||||
return d.listInterceptsPage("", page, size, filter)
|
||||
}
|
||||
|
||||
// ListTaskIntercepts returns all intercept_pending rows for a specific task (newest first).
|
||||
func (d *DB) ListTaskIntercepts(taskID string) ([]InterceptApprovalRow, error) {
|
||||
rows, err := d.Query(approvalRowSelect+` WHERE ip.task_id=$1 ORDER BY ip.created_at DESC`, taskID)
|
||||
return d.ListTaskInterceptsLimit(taskID, 0)
|
||||
}
|
||||
|
||||
// ListTaskInterceptsLimit returns up to limit intercept_pending rows for a
|
||||
// specific task (newest first). limit <= 0 returns all rows.
|
||||
func (d *DB) ListTaskInterceptsLimit(taskID string, limit int) ([]InterceptApprovalRow, error) {
|
||||
q := approvalRowSelect + ` WHERE ip.task_id=$1 ORDER BY ip.created_at DESC, ip.id DESC`
|
||||
args := []any{taskID}
|
||||
if limit > 0 {
|
||||
q += ` LIMIT $2`
|
||||
args = append(args, limit)
|
||||
}
|
||||
rows, err := d.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -323,11 +412,37 @@ func (d *DB) ListTaskIntercepts(taskID string) ([]InterceptApprovalRow, error) {
|
||||
}
|
||||
|
||||
// ListTaskInterceptsPage is the paginated variant of ListTaskIntercepts.
|
||||
func (d *DB) ListTaskInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
|
||||
func (d *DB) ListTaskInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
|
||||
return d.listInterceptsPage(taskID, page, size, filter)
|
||||
}
|
||||
|
||||
func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
|
||||
// estimateInterceptTableRows reads PostgreSQL's live row estimate for
|
||||
// intercept_pending without scanning the table.
|
||||
func (d *DB) estimateInterceptTableRows() (int64, error) {
|
||||
var relTuples, liveTuples, deadTuples int64
|
||||
err := d.QueryRow(`
|
||||
SELECT
|
||||
CASE WHEN c.reltuples >= 0 THEN c.reltuples::bigint ELSE -1 END,
|
||||
pg_stat_get_live_tuples(c.oid),
|
||||
pg_stat_get_dead_tuples(c.oid)
|
||||
FROM pg_class c
|
||||
WHERE c.oid = 'intercept_pending'::regclass`).Scan(&relTuples, &liveTuples, &deadTuples)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if liveTuples > 0 {
|
||||
return liveTuples, nil
|
||||
}
|
||||
if liveTuples == 0 && deadTuples > 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if relTuples > 0 {
|
||||
return relTuples, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
@@ -359,13 +474,15 @@ func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptA
|
||||
conditions = append(conditions, "ip.created_at < ($"+fmt.Sprint(len(args))+"::date + INTERVAL '1 day')")
|
||||
}
|
||||
search := strings.TrimSpace(filter.Search)
|
||||
hasTextSearch := false
|
||||
if strings.HasPrefix(search, "#") {
|
||||
id, err := strconv.ParseInt(strings.TrimPrefix(search, "#"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return nil, 0, fmt.Errorf("审批编号必须为 # 后接正整数")
|
||||
return InterceptApprovalPage{}, fmt.Errorf("审批编号必须为 # 后接正整数")
|
||||
}
|
||||
add("ip.id", strconv.FormatInt(id, 10))
|
||||
} else if search != "" {
|
||||
hasTextSearch = true
|
||||
// Treat SQL LIKE metacharacters literally, including URL percent escapes.
|
||||
pattern := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(search)
|
||||
args = append(args, "%"+pattern+"%")
|
||||
@@ -391,33 +508,96 @@ func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptA
|
||||
if len(conditions) > 0 {
|
||||
where = " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
var total int
|
||||
countFrom := "FROM intercept_pending ip"
|
||||
if search != "" && !strings.HasPrefix(search, "#") {
|
||||
countFrom = approvalRowJoins
|
||||
}
|
||||
if err := d.QueryRow("SELECT COUNT(*) "+countFrom+where, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
selectClause := approvalRowSelect
|
||||
if hasTextSearch {
|
||||
selectClause = approvalRowSearchSelect
|
||||
}
|
||||
limitArg := len(args) + 1
|
||||
offsetArg := limitArg + 1
|
||||
dataQ := approvalRowSelect + where +
|
||||
dataQ := selectClause + where +
|
||||
" ORDER BY ip.created_at DESC, ip.id DESC LIMIT $" + fmt.Sprint(limitArg) +
|
||||
" OFFSET $" + fmt.Sprint(offsetArg)
|
||||
args = append(args, size, offset)
|
||||
rows, err := d.Query(dataQ, args...)
|
||||
dataArgs := make([]any, 0, len(args)+2)
|
||||
dataArgs = append(dataArgs, args...)
|
||||
dataArgs = append(dataArgs, size+1, offset)
|
||||
rows, err := d.Query(dataQ, dataArgs...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
return InterceptApprovalPage{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []InterceptApprovalRow{}
|
||||
for rows.Next() {
|
||||
var r InterceptApprovalRow
|
||||
if err := scanInterceptApprovalRow(rows, &r); err != nil {
|
||||
return nil, 0, err
|
||||
return InterceptApprovalPage{}, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, total, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return InterceptApprovalPage{}, err
|
||||
}
|
||||
|
||||
hasMore := len(out) > size
|
||||
if hasMore {
|
||||
out = out[:size]
|
||||
}
|
||||
// Fast path: when we already hit the end of the result set on a non-empty
|
||||
// page (or page 1), the exact total is known without a separate COUNT query.
|
||||
if !hasMore && (len(out) > 0 || offset == 0) {
|
||||
return InterceptApprovalPage{
|
||||
Items: out,
|
||||
Total: offset + len(out),
|
||||
HasMore: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
capLimit := interceptExactCountCap
|
||||
if capLimit < offset+size {
|
||||
capLimit = offset + size
|
||||
}
|
||||
// For large unfiltered global queries, use PostgreSQL's catalog estimate
|
||||
// instead of scanning the entire intercept_pending table.
|
||||
if len(conditions) == 0 {
|
||||
if est, estErr := d.estimateInterceptTableRows(); estErr == nil && est > int64(capLimit) {
|
||||
total := int(est)
|
||||
if hasMore && total <= offset+len(out) {
|
||||
total = offset + len(out) + 1
|
||||
}
|
||||
return InterceptApprovalPage{
|
||||
Items: out,
|
||||
Total: total,
|
||||
TotalApproximate: true,
|
||||
HasMore: hasMore,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
countFrom := "FROM intercept_pending ip"
|
||||
if hasTextSearch {
|
||||
countFrom = approvalRowSearchJoins
|
||||
}
|
||||
capArg := len(args) + 1
|
||||
countArgs := make([]any, 0, len(args)+1)
|
||||
countArgs = append(countArgs, args...)
|
||||
countArgs = append(countArgs, capLimit+1)
|
||||
var counted int
|
||||
countQ := "SELECT COUNT(*) FROM (SELECT 1 " + countFrom + where + " LIMIT $" + fmt.Sprint(capArg) + ") s"
|
||||
if err := d.QueryRow(countQ, countArgs...).Scan(&counted); err != nil {
|
||||
return InterceptApprovalPage{}, err
|
||||
}
|
||||
if counted > capLimit {
|
||||
return InterceptApprovalPage{
|
||||
Items: out,
|
||||
Total: capLimit,
|
||||
TotalApproximate: true,
|
||||
TotalCapped: true,
|
||||
HasMore: hasMore,
|
||||
}, nil
|
||||
}
|
||||
return InterceptApprovalPage{
|
||||
Items: out,
|
||||
Total: counted,
|
||||
HasMore: hasMore,
|
||||
}, nil
|
||||
}
|
||||
+114
-34
@@ -21,10 +21,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_rules WHERE id=$1`, rule.ID) })
|
||||
filter := InterceptApprovalFilter{Status: "denied", DecisionSource: "model"}
|
||||
_, baseline, err := d.ListAllInterceptsPage(1, 20, filter)
|
||||
basePage, err := d.ListAllInterceptsPage(1, 20, filter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
baseline := basePage.Total
|
||||
expected := []int64{}
|
||||
for _, task := range []string{scope, scope + "-other"} {
|
||||
copies := 3
|
||||
@@ -85,11 +86,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rows, total, err := d.ListTaskInterceptsPage(scope, 1, 100, tc.filter)
|
||||
if err != nil || total != tc.want || len(rows) != tc.want {
|
||||
t.Fatalf("count=%d rows=%d err=%v", total, len(rows), err)
|
||||
res, err := d.ListTaskInterceptsPage(scope, 1, 100, tc.filter)
|
||||
if err != nil || res.Total != tc.want || len(res.Items) != tc.want {
|
||||
t.Fatalf("count=%d rows=%d err=%v", res.Total, len(res.Items), err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
for _, r := range res.Items {
|
||||
if r.TaskID == nil || *r.TaskID != scope || tc.filter.Status != "" && r.Status != tc.filter.Status || tc.filter.DecisionSource != "" && r.DecisionSource != tc.filter.DecisionSource {
|
||||
t.Fatalf("nonmatching row: %+v", r)
|
||||
}
|
||||
@@ -99,29 +100,32 @@ func TestInterceptApprovalFilters(t *testing.T) {
|
||||
slices.Reverse(expected)
|
||||
var seen []int64
|
||||
for page := 1; page <= 2; page++ {
|
||||
rows, total, err := d.ListTaskInterceptsPage(scope, page, 2, filter)
|
||||
if err != nil || total != 3 {
|
||||
t.Fatalf("page %d total=%d err=%v", page, total, err)
|
||||
res, err := d.ListTaskInterceptsPage(scope, page, 2, filter)
|
||||
if err != nil || res.Total != 3 {
|
||||
t.Fatalf("page %d total=%d err=%v", page, res.Total, err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if wantMore := page == 1; res.HasMore != wantMore {
|
||||
t.Fatalf("page %d hasMore=%v want=%v", page, res.HasMore, wantMore)
|
||||
}
|
||||
for _, r := range res.Items {
|
||||
seen = append(seen, r.ID)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(seen, expected) {
|
||||
t.Fatalf("unstable combined-filter pagination: got %v want %v", seen, expected)
|
||||
}
|
||||
rows, total, err := d.ListTaskInterceptsPage(scope, 3, 2, filter)
|
||||
if err != nil || len(rows) != 0 || total != 3 {
|
||||
t.Fatalf("empty page count=%d rows=%d err=%v", total, len(rows), err)
|
||||
res, err := d.ListTaskInterceptsPage(scope, 3, 2, filter)
|
||||
if err != nil || len(res.Items) != 0 || res.Total != 3 || res.HasMore {
|
||||
t.Fatalf("empty page count=%d rows=%d hasMore=%v err=%v", res.Total, len(res.Items), res.HasMore, err)
|
||||
}
|
||||
_, total, err = d.ListAllInterceptsPage(1, 100, filter)
|
||||
if err != nil || total != baseline+4 {
|
||||
t.Fatalf("global filter count=%d want=%d err=%v", total, baseline+4, err)
|
||||
globalRes, err := d.ListAllInterceptsPage(1, 100, filter)
|
||||
if err != nil || globalRes.Total != baseline+4 {
|
||||
t.Fatalf("global filter count=%d want=%d err=%v", globalRes.Total, baseline+4, err)
|
||||
}
|
||||
// Values must remain SQL parameters even for direct store callers.
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Status: "denied' OR 1=1 --"})
|
||||
if err != nil || total != 0 || len(rows) != 0 {
|
||||
t.Fatalf("invalid value escaped filter: %d %v", total, err)
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Status: "denied' OR 1=1 --"})
|
||||
if err != nil || res.Total != 0 || len(res.Items) != 0 {
|
||||
t.Fatalf("invalid value escaped filter: %d %v", res.Total, err)
|
||||
}
|
||||
// A rule's persisted source survives deletion of its associated rule.
|
||||
_, err = d.Exec(`UPDATE intercept_pending SET decision_source='rule' WHERE task_id=$1 AND rule_id=$2`, scope, rule.ID)
|
||||
@@ -131,11 +135,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
|
||||
if err = d.DeleteInterceptRule(rule.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 100, InterceptApprovalFilter{DecisionSource: "rule"})
|
||||
if err != nil || total != 12 {
|
||||
t.Fatalf("deleted-rule source count=%d err=%v", total, err)
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 100, InterceptApprovalFilter{DecisionSource: "rule"})
|
||||
if err != nil || res.Total != 12 {
|
||||
t.Fatalf("deleted-rule source count=%d err=%v", res.Total, err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
for _, r := range res.Items {
|
||||
if r.RuleID != nil || r.DecisionSource != "rule" {
|
||||
t.Fatal("deleted rule lost its source")
|
||||
}
|
||||
@@ -146,22 +150,98 @@ func TestInterceptApprovalFilters(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "example.test"})
|
||||
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
|
||||
t.Fatalf("snapshot search total=%d rows=%d err=%v", total, len(rows), err)
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "example.test"})
|
||||
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
|
||||
t.Fatalf("snapshot search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
|
||||
}
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "100%"})
|
||||
if err != nil || total != 1 || len(rows) != 1 {
|
||||
t.Fatalf("literal percent search total=%d rows=%d err=%v", total, len(rows), err)
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "100%"})
|
||||
if err != nil || res.Total != 1 || len(res.Items) != 1 {
|
||||
t.Fatalf("literal percent search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
|
||||
}
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "#" + strconv.FormatInt(searchID, 10)})
|
||||
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
|
||||
t.Fatalf("id search total=%d rows=%d err=%v", total, len(rows), err)
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "#" + strconv.FormatInt(searchID, 10)})
|
||||
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
|
||||
t.Fatalf("id search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
|
||||
}
|
||||
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{
|
||||
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{
|
||||
Search: "example.test", CreatedFrom: "2099-01-01", CreatedTo: "2099-01-01",
|
||||
})
|
||||
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
|
||||
t.Fatalf("date search total=%d rows=%d err=%v", total, len(rows), err)
|
||||
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
|
||||
t.Fatalf("date search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterceptPendingSummaryAndBoundedCount(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
scope := "approval-summary-" + t.Name()
|
||||
other := scope + "-other"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id IN ($1,$2)`, scope, other) })
|
||||
|
||||
baseCount, err := d.CountPendingIntercepts()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, agent := range []string{"mainagent", "work#1 · #101", "work#1 · #101", "planner"} {
|
||||
if _, err := d.CreateInterceptPending(0, 0, scope, agent, "Bash", []byte(`{"command":"id"}`), "ask"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := d.CreateInterceptPending(0, 0, other, "mainagent", "Bash", []byte(`{"command":"id"}`), "ask"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 8 {
|
||||
if _, err := d.CreateDecidedIntercept(0, 0, scope, "work#2 · #202", "Bash", []byte(`{"command":"ls"}`), "allowed", "ok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
globalCount, err := d.CountPendingIntercepts()
|
||||
if err != nil || globalCount != baseCount+5 {
|
||||
t.Fatalf("CountPendingIntercepts=%d want=%d err=%v", globalCount, baseCount+5, err)
|
||||
}
|
||||
summary, err := d.TaskPendingInterceptSummary(scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantAgents := []string{"mainagent", "planner", "work#1 · #101"}
|
||||
if summary.Count != 4 || !slices.Equal(summary.AgentNames, wantAgents) {
|
||||
t.Fatalf("TaskPendingInterceptSummary=%+v want count=4 agents=%v", summary, wantAgents)
|
||||
}
|
||||
taskPending, err := d.ListPendingInterceptsByTask(scope)
|
||||
if err != nil || len(taskPending) != 4 {
|
||||
t.Fatalf("ListPendingInterceptsByTask len=%d err=%v", len(taskPending), err)
|
||||
}
|
||||
limited, err := d.ListTaskInterceptsLimit(scope, 5)
|
||||
if err != nil || len(limited) != 5 {
|
||||
t.Fatalf("ListTaskInterceptsLimit len=%d err=%v", len(limited), err)
|
||||
}
|
||||
|
||||
// Exercise bounded count cap and unfiltered approximate estimate without
|
||||
// inserting tens of thousands of rows.
|
||||
prevCap := interceptExactCountCap
|
||||
interceptExactCountCap = 5
|
||||
t.Cleanup(func() { interceptExactCountCap = prevCap })
|
||||
|
||||
capped, err := d.ListTaskInterceptsPage(scope, 1, 3, InterceptApprovalFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(capped.Items) != 3 || !capped.HasMore || !capped.TotalApproximate || !capped.TotalCapped || capped.Total != 5 {
|
||||
t.Fatalf("capped task page=%+v", capped)
|
||||
}
|
||||
|
||||
if _, err := d.Exec(`ANALYZE intercept_pending`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approx, err := d.ListAllInterceptsPage(1, 3, InterceptApprovalFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(approx.Items) != 3 || !approx.HasMore || !approx.TotalApproximate || approx.TotalCapped || approx.Total < 13 {
|
||||
t.Fatalf("unfiltered approximate page=%+v", approx)
|
||||
}
|
||||
}
|
||||
@@ -1146,6 +1146,10 @@ CREATE TABLE IF NOT EXISTS intercept_pending (
|
||||
CREATE INDEX IF NOT EXISTS idx_intercept_pending_status ON intercept_pending(status, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_intercept_pending_task ON intercept_pending(task_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_intercept_pending_created ON intercept_pending(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_intercept_pending_pending_task
|
||||
ON intercept_pending(task_id, created_at DESC)
|
||||
INCLUDE (agent_name)
|
||||
WHERE status = 'pending';
|
||||
-- 补旧库:reason 列(已发版,加列要带 IF NOT EXISTS)。
|
||||
ALTER TABLE intercept_pending ADD COLUMN IF NOT EXISTS reason TEXT NOT NULL DEFAULT '';
|
||||
-- Detail payloads are lazy-loaded; NULL preserves the meaning of legacy history.
|
||||
|
||||
+6
-10
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"}
|
||||
|
||||
+59
-9
@@ -258,7 +258,16 @@ func (s *Server) interceptListPending(w http.ResponseWriter, r *http.Request) {
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
pending, err := pg.ListPendingIntercepts()
|
||||
taskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
|
||||
var (
|
||||
pending []db.InterceptPending
|
||||
err error
|
||||
)
|
||||
if taskID != "" {
|
||||
pending, err = pg.ListPendingInterceptsByTask(taskID)
|
||||
} else {
|
||||
pending, err = pg.ListPendingIntercepts()
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
@@ -269,6 +278,32 @@ func (s *Server) interceptListPending(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"pending": pending})
|
||||
}
|
||||
|
||||
func (s *Server) interceptPendingSummary(w http.ResponseWriter, r *http.Request) {
|
||||
pg := s.pg(w)
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
taskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
|
||||
if taskID == "" {
|
||||
count, err := pg.CountPendingIntercepts()
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"count": count})
|
||||
return
|
||||
}
|
||||
summary, err := pg.TaskPendingInterceptSummary(taskID)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if summary.AgentNames == nil {
|
||||
summary.AgentNames = []string{}
|
||||
}
|
||||
writeJSON(w, 200, summary)
|
||||
}
|
||||
|
||||
func (s *Server) interceptGetOne(w http.ResponseWriter, r *http.Request) {
|
||||
pg := s.pg(w)
|
||||
if pg == nil {
|
||||
@@ -308,7 +343,7 @@ func (s *Server) interceptListTaskItems(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
if q.Get("page") == "" && q.Get("size") == "" && filter == (db.InterceptApprovalFilter{}) {
|
||||
items, err := pg.ListTaskIntercepts(taskID)
|
||||
items, err := pg.ListTaskInterceptsLimit(taskID, 200)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
@@ -320,15 +355,12 @@ func (s *Server) interceptListTaskItems(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
page, size := interceptPageParams(q)
|
||||
items, total, err := pg.ListTaskInterceptsPage(taskID, page, size, filter)
|
||||
res, err := pg.ListTaskInterceptsPage(taskID, page, size, filter)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []db.InterceptApprovalRow{}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"items": items, "total": total, "page": page, "page_size": size})
|
||||
writeInterceptPage(w, res, page, size)
|
||||
}
|
||||
|
||||
func (s *Server) interceptHistory(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -355,15 +387,33 @@ func (s *Server) interceptHistory(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
page, size := interceptPageParams(q)
|
||||
items, total, err := pg.ListAllInterceptsPage(page, size, filter)
|
||||
res, err := pg.ListAllInterceptsPage(page, size, filter)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeInterceptPage(w, res, page, size)
|
||||
}
|
||||
|
||||
func writeInterceptPage(w http.ResponseWriter, res db.InterceptApprovalPage, page, size int) {
|
||||
items := res.Items
|
||||
if items == nil {
|
||||
items = []db.InterceptApprovalRow{}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"items": items, "total": total, "page": page, "page_size": size})
|
||||
payload := map[string]any{
|
||||
"items": items,
|
||||
"total": res.Total,
|
||||
"has_more": res.HasMore,
|
||||
"page": page,
|
||||
"page_size": size,
|
||||
}
|
||||
if res.TotalApproximate {
|
||||
payload["total_approximate"] = true
|
||||
}
|
||||
if res.TotalCapped {
|
||||
payload["total_capped"] = true
|
||||
}
|
||||
writeJSON(w, 200, payload)
|
||||
}
|
||||
|
||||
func interceptFilterParams(q url.Values) (db.InterceptApprovalFilter, error) {
|
||||
|
||||
@@ -63,10 +63,11 @@ func TestInterceptFilterHTTP(t *testing.T) {
|
||||
}
|
||||
scope := "approval-http-filter"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id IN ($1,$2)`, scope, scope+"-other") })
|
||||
_, baseline, err := d.ListAllInterceptsPage(1, 20, db.InterceptApprovalFilter{Status: "denied", DecisionSource: "model"})
|
||||
basePage, err := d.ListAllInterceptsPage(1, 20, db.InterceptApprovalFilter{Status: "denied", DecisionSource: "model"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
baseline := basePage.Total
|
||||
for _, state := range []string{"pending", "allowed", "denied", "timeout"} {
|
||||
if _, err := d.CreateDecidedIntercept(0, 0, scope, "test", "Bash", []byte(`{}`), state, "[模型] fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -143,4 +144,50 @@ func TestInterceptFilterHTTP(t *testing.T) {
|
||||
t.Fatalf("%s: %d %s", tc.query, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Pending summary endpoints must require auth and return lightweight counts
|
||||
// without historical rows.
|
||||
if rec := do("/api/intercept/pending/summary", false); rec.Code != 401 {
|
||||
t.Fatalf("unprotected summary: %d", rec.Code)
|
||||
}
|
||||
rec := do("/api/intercept/pending/summary", true)
|
||||
var globalSummary struct {
|
||||
Count int `json:"count"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &globalSummary) != nil || globalSummary.Count < 1 {
|
||||
t.Fatalf("global summary: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = do("/api/intercept/pending/summary?task_id="+scope, true)
|
||||
var taskSummary struct {
|
||||
Count int `json:"count"`
|
||||
AgentNames []string `json:"agent_names"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &taskSummary) != nil || taskSummary.Count != 1 || len(taskSummary.AgentNames) != 1 || taskSummary.AgentNames[0] != "test" {
|
||||
t.Fatalf("task summary: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = do("/api/intercept/pending?task_id="+scope, true)
|
||||
var taskPending struct {
|
||||
Pending []db.InterceptPending `json:"pending"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &taskPending) != nil || len(taskPending.Pending) != 1 {
|
||||
t.Fatalf("task pending: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Unpaginated task history must stay bounded so large tasks never dump full history.
|
||||
bigScope := scope + "-cap"
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, bigScope) })
|
||||
if _, err := d.Exec(`
|
||||
INSERT INTO intercept_pending (task_id, agent_name, tool_name, tool_input, status, reason, decision_source)
|
||||
SELECT $1, 'worker', 'Bash', '{}'::jsonb, 'allowed', 'ok', 'rule'
|
||||
FROM generate_series(1, 205)`, bigScope); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = do("/api/intercept/task/"+bigScope, true)
|
||||
var cappedTask struct {
|
||||
Items []db.InterceptApprovalRow `json:"items"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &cappedTask) != nil || len(cappedTask.Items) != 200 || cappedTask.Total != 200 {
|
||||
t.Fatalf("unpaginated task cap: %d len=%d total=%d", rec.Code, len(cappedTask.Items), cappedTask.Total)
|
||||
}
|
||||
}
|
||||
+4
-15
@@ -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")
|
||||
}
|
||||
|
||||
+4
-54
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -553,7 +553,7 @@ func (s *Server) seedOrchestrationTools() {
|
||||
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 {
|
||||
|
||||
+7
-6
@@ -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(仅空时)
|
||||
@@ -1152,6 +1152,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/asset-intercept/rules/{id}/toggle", s.assetInterceptToggleRule)
|
||||
|
||||
mux.HandleFunc("GET /api/intercept/pending", s.interceptListPending)
|
||||
mux.HandleFunc("GET /api/intercept/pending/summary", s.interceptPendingSummary)
|
||||
mux.HandleFunc("GET /api/intercept/pending/{id}", s.interceptGetOne)
|
||||
mux.HandleFunc("POST /api/intercept/pending/{id}/decide", s.interceptDecide)
|
||||
mux.HandleFunc("GET /api/intercept/history", s.interceptHistory)
|
||||
@@ -3827,11 +3828,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),
|
||||
|
||||
+4
-9
@@ -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
|
||||
|
||||
@@ -161,21 +161,36 @@ function NavItem({ item, isItemActive, isSubItemActive, isSubmenuOpen }: NavItem
|
||||
);
|
||||
}
|
||||
|
||||
// InterceptPendingBadge polls /api/intercept/pending every 5 s and shows a red
|
||||
// count badge when there are unresolved approval requests.
|
||||
// InterceptPendingBadge polls /api/intercept/pending/summary every 5 s (while
|
||||
// visible) and shows an amber count badge when there are unresolved requests.
|
||||
function InterceptPendingBadge() {
|
||||
const [count, setCount] = React.useState(0);
|
||||
React.useEffect(() => {
|
||||
let live = true;
|
||||
let inFlight = false;
|
||||
async function poll() {
|
||||
if (inFlight || document.hidden) return;
|
||||
inFlight = true;
|
||||
try {
|
||||
const list = await api.interceptPending();
|
||||
if (live) setCount(list.length);
|
||||
} catch { /* ignore */ }
|
||||
const summary = await api.interceptPendingSummary();
|
||||
if (live) setCount(summary.count);
|
||||
} catch {
|
||||
/* ignore */
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
}
|
||||
poll();
|
||||
const t = setInterval(poll, 5000);
|
||||
return () => { live = false; clearInterval(t); };
|
||||
void poll();
|
||||
const t = setInterval(() => void poll(), 5000);
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) void poll();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
live = false;
|
||||
clearInterval(t);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, []);
|
||||
if (count === 0) return null;
|
||||
return (
|
||||
|
||||
@@ -59,7 +59,6 @@ import type {
|
||||
Activity,
|
||||
ChatAttachment,
|
||||
IntentAsset,
|
||||
InterceptApprovalRow,
|
||||
Session,
|
||||
SessionStatus,
|
||||
SessionTokenUsage,
|
||||
@@ -491,7 +490,17 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string; requestedSession?: string }) {
|
||||
const EMPTY_PENDING_AGENTS: string[] = [];
|
||||
|
||||
export function SessionsTab({
|
||||
taskId,
|
||||
requestedSession = "",
|
||||
pendingAgentNames = EMPTY_PENDING_AGENTS,
|
||||
}: {
|
||||
taskId: string;
|
||||
requestedSession?: string;
|
||||
pendingAgentNames?: string[];
|
||||
}) {
|
||||
const { ui, liveUI } = useUITranslation();
|
||||
|
||||
const approvalFocus = useApprovalFocus({ taskId });
|
||||
@@ -676,8 +685,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
|
||||
const [taskTokens, setTaskTokens] = React.useState<TokenTotal | null>(null);
|
||||
const [sessionTokens, setSessionTokens] = React.useState<Record<string, SessionTokenUsage>>({});
|
||||
const [llmResolutions, setLLMResolutions] = React.useState<TaskLLMResolutions | null>(null);
|
||||
// Pending intercept requests for this task — used to show warning icons on sessions.
|
||||
const [pendingIntercepts, setPendingIntercepts] = React.useState<InterceptApprovalRow[]>([]);
|
||||
|
||||
// Refs backing SSE/loading without re-render churn.
|
||||
const snapshotRef = React.useRef(0); // task-level snapshot cursor → SSE since=
|
||||
@@ -885,25 +892,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
|
||||
};
|
||||
}, [taskId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
let alive = true;
|
||||
const load = () =>
|
||||
api
|
||||
.interceptTask(taskId)
|
||||
.then((rows) => {
|
||||
if (alive) setPendingIntercepts(rows.filter((r) => r.status === "pending"));
|
||||
})
|
||||
.catch(() => {
|
||||
// Polling is best-effort; the next interval retries automatically.
|
||||
});
|
||||
void load();
|
||||
const t = setInterval(load, 5000);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, [taskId]);
|
||||
|
||||
// Re-render on a timer so "streaming" liveness recomputes as activity goes stale.
|
||||
const [, setTick] = React.useState(0);
|
||||
React.useEffect(() => {
|
||||
@@ -1225,16 +1213,16 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
|
||||
const hasPendingForSession = React.useCallback(
|
||||
(s: Session): boolean => {
|
||||
if (s.inherited) return false;
|
||||
if (!pendingIntercepts.length) return false;
|
||||
if (s.role === "mainagent") return pendingIntercepts.some((r) => r.agent_name === "mainagent");
|
||||
if (s.role === "planner") return pendingIntercepts.some((r) => r.agent_name === "planner");
|
||||
if (!pendingAgentNames.length) return false;
|
||||
if (s.role === "mainagent") return pendingAgentNames.includes("mainagent");
|
||||
if (s.role === "planner") return pendingAgentNames.includes("planner");
|
||||
// Worker: extract intent ID from "work#N · #<intentID>"
|
||||
return pendingIntercepts.some((r) => {
|
||||
const m = r.agent_name.match(/·\s*#(\d+)$/);
|
||||
return pendingAgentNames.some((agentName) => {
|
||||
const m = agentName.match(/·\s*#(\d+)$/);
|
||||
return m ? m[1] === s.intent_id : false;
|
||||
});
|
||||
},
|
||||
[pendingIntercepts],
|
||||
[pendingAgentNames],
|
||||
);
|
||||
|
||||
// Liveness from each session's last-seen activity time (kept fresh by the 1.5s tick).
|
||||
|
||||
@@ -314,6 +314,7 @@ function TaskDetailInner() {
|
||||
if (TABS(liveUI).some((item) => item.value === normalizedRequestedTab)) setTab(normalizedRequestedTab);
|
||||
}, [normalizedRequestedTab, liveUI]);
|
||||
const [interceptPendingCount, setInterceptPendingCount] = React.useState(0);
|
||||
const [pendingAgentNames, setPendingAgentNames] = React.useState<string[]>([]);
|
||||
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
|
||||
const [archiving, setArchiving] = React.useState(false);
|
||||
|
||||
@@ -326,20 +327,36 @@ function TaskDetailInner() {
|
||||
|
||||
React.useEffect(() => {
|
||||
let alive = true;
|
||||
const load = () =>
|
||||
let inFlight = false;
|
||||
setInterceptPendingCount(0);
|
||||
setPendingAgentNames([]);
|
||||
const loadSummary = () => {
|
||||
if (inFlight || document.hidden) return;
|
||||
inFlight = true;
|
||||
api
|
||||
.interceptTask(id)
|
||||
.then((rows) => {
|
||||
if (alive) setInterceptPendingCount(rows.filter((r) => r.status === "pending").length);
|
||||
.interceptPendingSummary(id)
|
||||
.then((summary) => {
|
||||
if (!alive) return;
|
||||
setInterceptPendingCount(summary.count);
|
||||
setPendingAgentNames(summary.agent_names);
|
||||
})
|
||||
.catch(() => {
|
||||
// Polling is best-effort; the next interval retries automatically.
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight = false;
|
||||
});
|
||||
void load();
|
||||
const t = setInterval(load, 5000);
|
||||
};
|
||||
loadSummary();
|
||||
const t = setInterval(loadSummary, 5000);
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) loadSummary();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
@@ -598,7 +615,12 @@ function TaskDetailInner() {
|
||||
{/* Tab content */}
|
||||
<div className="flex-1 p-4 lg:p-6">
|
||||
<TabsContent value="sessions" className="mt-0">
|
||||
<SessionsTab key={id} taskId={id} requestedSession={searchParams.get("session") ?? ""} />
|
||||
<SessionsTab
|
||||
key={id}
|
||||
taskId={id}
|
||||
requestedSession={searchParams.get("session") ?? ""}
|
||||
pendingAgentNames={pendingAgentNames}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="traffic" className="mt-0">
|
||||
<TrafficHistory taskId={id} />
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -34,6 +34,7 @@ import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type {
|
||||
InterceptApprovalFilter,
|
||||
InterceptApprovalPage,
|
||||
InterceptApprovalRow,
|
||||
InterceptAudit,
|
||||
InterceptDetail,
|
||||
@@ -902,6 +903,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [pageSize, setPageSize] = React.useState(20);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [totalApproximate, setTotalApproximate] = React.useState(false);
|
||||
const [totalCapped, setTotalCapped] = React.useState(false);
|
||||
const [hasMore, setHasMore] = React.useState(false);
|
||||
const [filter, setFilter] = React.useState<InterceptApprovalFilter>({});
|
||||
const [searchText, setSearchText] = React.useState("");
|
||||
const [fromDate, setFromDate] = React.useState("");
|
||||
@@ -913,6 +917,8 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const [deciding, setDeciding] = React.useState(false);
|
||||
const [revision, setRevision] = React.useState(0);
|
||||
const request = React.useRef(0);
|
||||
const inFlight = React.useRef<number | null>(null);
|
||||
const pendingKeyRef = React.useRef<string | null>(null);
|
||||
const decisionLock = React.useRef(false);
|
||||
const filterID = React.useId();
|
||||
const filtered = Boolean(filter.status || filter.decision_source || filter.q || filter.from || filter.to);
|
||||
@@ -925,37 +931,77 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
}, [taskId]);
|
||||
|
||||
const load = React.useCallback(
|
||||
async (manual = false) => {
|
||||
async (mode: "full" | "manual" | "poll" = "full") => {
|
||||
if (mode === "poll" && (document.hidden || inFlight.current !== null)) return;
|
||||
const id = ++request.current;
|
||||
if (manual) setRefreshing(true);
|
||||
inFlight.current = id;
|
||||
if (mode === "manual") setRefreshing(true);
|
||||
const fetchHistory = () =>
|
||||
taskId
|
||||
? api.interceptTaskPage(taskId, page, pageSize, filter)
|
||||
: api.interceptHistoryPage(page, pageSize, filter);
|
||||
const applyHistory = (value: InterceptApprovalPage) => {
|
||||
setRows(value.items);
|
||||
setTotal(value.total);
|
||||
setTotalApproximate(Boolean(value.total_approximate));
|
||||
setTotalCapped(Boolean(value.total_capped));
|
||||
setHasMore(Boolean(value.has_more));
|
||||
setError("");
|
||||
};
|
||||
const pendingSignature = (list: InterceptPending[]) =>
|
||||
list
|
||||
.map((row) => row.id)
|
||||
.sort((a, b) => a - b)
|
||||
.join(",");
|
||||
try {
|
||||
// The approval queue is independent of the current history page and its
|
||||
// filter. Older requests must remain actionable even when newer decisions
|
||||
// fill the page or a filter would hide them.
|
||||
const [history, pending] = await Promise.allSettled([
|
||||
taskId
|
||||
? api.interceptTaskPage(taskId, page, pageSize, filter)
|
||||
: api.interceptHistoryPage(page, pageSize, filter),
|
||||
api.interceptPending(),
|
||||
]);
|
||||
if (id !== request.current) return;
|
||||
if (history.status === "fulfilled") {
|
||||
setRows(history.value.items);
|
||||
setTotal(history.value.total);
|
||||
setError("");
|
||||
// Keep the actionable pending queue fresh on every tick. Only auto-refresh
|
||||
// history on page 1 without a free-text search (or when pending IDs change)
|
||||
// so background polls neither re-run full-text scans nor shift deeper pages.
|
||||
const pollHistory = mode !== "poll" || (page === 1 && !filter.q);
|
||||
if (pollHistory) {
|
||||
// The approval queue is independent of the current history page and its
|
||||
// filter. Older requests must remain actionable even when newer decisions
|
||||
// fill the page or a filter would hide them.
|
||||
const [history, pending] = await Promise.allSettled([fetchHistory(), api.interceptPending(taskId)]);
|
||||
if (id !== request.current) return;
|
||||
if (history.status === "fulfilled") {
|
||||
applyHistory(history.value);
|
||||
} else {
|
||||
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
}
|
||||
if (pending.status === "fulfilled") {
|
||||
pendingKeyRef.current = pendingSignature(pending.value);
|
||||
setPendingRows(pending.value);
|
||||
setPendingError("");
|
||||
} else {
|
||||
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
}
|
||||
} else {
|
||||
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
try {
|
||||
const pending = await api.interceptPending(taskId);
|
||||
if (id !== request.current) return;
|
||||
const nextKey = pendingSignature(pending);
|
||||
const changed = pendingKeyRef.current !== null && nextKey !== pendingKeyRef.current;
|
||||
pendingKeyRef.current = nextKey;
|
||||
setPendingRows(pending);
|
||||
setPendingError("");
|
||||
if (changed) {
|
||||
try {
|
||||
const history = await fetchHistory();
|
||||
if (id === request.current) applyHistory(history);
|
||||
} catch (e) {
|
||||
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (id === request.current) setPendingError((e as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
}
|
||||
}
|
||||
if (pending.status === "fulfilled") {
|
||||
setPendingRows(pending.value);
|
||||
setPendingError("");
|
||||
} else {
|
||||
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
}
|
||||
if (manual) setRevision((v) => v + 1);
|
||||
if (mode === "manual") setRevision((v) => v + 1);
|
||||
} catch (e) {
|
||||
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
|
||||
} finally {
|
||||
if (inFlight.current === id) inFlight.current = null;
|
||||
if (id === request.current) {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
@@ -968,11 +1014,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
latestLoad.current = load;
|
||||
|
||||
React.useEffect(() => {
|
||||
void load();
|
||||
const timer = setInterval(() => void load(), 5000);
|
||||
void load("full");
|
||||
const timer = setInterval(() => void load("poll"), 5000);
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) void load("poll");
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
request.current++;
|
||||
inFlight.current = null;
|
||||
clearInterval(timer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
@@ -991,6 +1043,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
setPage(1);
|
||||
setRows([]);
|
||||
setTotal(0);
|
||||
setTotalApproximate(false);
|
||||
setTotalCapped(false);
|
||||
setHasMore(false);
|
||||
setError("");
|
||||
setLoading(true);
|
||||
};
|
||||
@@ -1013,6 +1068,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
setPage(1);
|
||||
setRows([]);
|
||||
setTotal(0);
|
||||
setTotalApproximate(false);
|
||||
setTotalCapped(false);
|
||||
setHasMore(false);
|
||||
setError("");
|
||||
setLoading(true);
|
||||
}, 300);
|
||||
@@ -1036,10 +1094,10 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
setRevision((v) => v + 1);
|
||||
toast.success(decision === "allowed" ? ui("screen.c90e80972b10bf") : ui("screen.846e5cf371bfdc"));
|
||||
// Re-fetch counts and rows: a decided item may no longer match the filter.
|
||||
await latestLoad.current(true);
|
||||
await latestLoad.current("manual");
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
await latestLoad.current(true);
|
||||
await latestLoad.current("manual");
|
||||
} finally {
|
||||
decisionLock.current = false;
|
||||
setDeciding(false);
|
||||
@@ -1056,6 +1114,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
...historyById.get(row.id),
|
||||
...row,
|
||||
}));
|
||||
let totalDisplay: string | number = total;
|
||||
if (totalCapped) totalDisplay = `${total}+`;
|
||||
else if (totalApproximate) totalDisplay = `~${total}`;
|
||||
const title = taskId ? ui("screen.b4c245b6421a35") : ui("screen.b75d0f43cd1eb7");
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-5">
|
||||
@@ -1069,7 +1130,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => void load(true)} disabled={loading || refreshing}>
|
||||
<Button variant="outline" size="sm" onClick={() => void load("manual")} disabled={loading || refreshing}>
|
||||
<RefreshCwIcon data-icon="inline-start" className={cn(refreshing && "animate-spin")} />
|
||||
{ui("screen.aee88743413144")}
|
||||
</Button>
|
||||
@@ -1217,7 +1278,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
<div className="border-b px-4 py-3 font-medium text-sm">
|
||||
{filtered ? ui("screen.479424539ce56d") : ui("screen.e4257920848098")}
|
||||
{ui("punctuation.da047c04c9")}
|
||||
{total}
|
||||
{totalDisplay}
|
||||
{ui("punctuation.f2e44c6c95")}
|
||||
{filter.q ? (
|
||||
<span className="ml-2 break-all font-normal text-muted-foreground text-xs">
|
||||
@@ -1260,6 +1321,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
total={total}
|
||||
totalApproximate={totalApproximate}
|
||||
totalCapped={totalCapped}
|
||||
hasMore={hasMore}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={changePageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
|
||||
@@ -13,6 +13,9 @@ interface TablePaginationProps {
|
||||
page: number; // 1-based
|
||||
pageSize: number;
|
||||
total: number; // total (after filtering)
|
||||
totalApproximate?: boolean;
|
||||
totalCapped?: boolean;
|
||||
hasMore?: boolean;
|
||||
onPageChange: (p: number) => void;
|
||||
onPageSizeChange: (s: number) => void;
|
||||
pageSizeOptions?: number[];
|
||||
@@ -35,15 +38,22 @@ export function TablePagination({
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalApproximate = false,
|
||||
totalCapped = false,
|
||||
hasMore = false,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
pageSizeOptions = [10, 20, 50],
|
||||
}: TablePaginationProps) {
|
||||
const { t } = useTranslation();
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize), hasMore ? page + 1 : 0);
|
||||
const safePage = Math.min(Math.max(1, page), totalPages);
|
||||
const from = total === 0 ? 0 : (safePage - 1) * pageSize + 1;
|
||||
const to = Math.min(safePage * pageSize, total);
|
||||
const hasItems = total > 0 || hasMore;
|
||||
const from = hasItems ? (safePage - 1) * pageSize + 1 : 0;
|
||||
const to = hasMore ? safePage * pageSize : Math.min(safePage * pageSize, total);
|
||||
let totalLabel: string | number = total;
|
||||
if (totalCapped) totalLabel = `${total}+`;
|
||||
else if (totalApproximate) totalLabel = `~${total}`;
|
||||
const onPageChangeRef = useRef(onPageChange);
|
||||
onPageChangeRef.current = onPageChange;
|
||||
|
||||
@@ -67,8 +77,8 @@ export function TablePagination({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span>{t("pagination.perPage")}</span>
|
||||
{total > 0 ? (
|
||||
<span className="tabular-nums">{t("pagination.range", { from, to, total, count: total })}</span>
|
||||
{hasItems ? (
|
||||
<span className="tabular-nums">{t("pagination.range", { from, to, total: totalLabel, count: total })}</span>
|
||||
) : (
|
||||
<span>{t("pagination.empty")}</span>
|
||||
)}
|
||||
|
||||
@@ -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"],
|
||||
|
||||
+40
-11
@@ -55,9 +55,11 @@ import type {
|
||||
IntelligencePage,
|
||||
IntentAsset,
|
||||
InterceptApprovalFilter,
|
||||
InterceptApprovalPage,
|
||||
InterceptApprovalRow,
|
||||
InterceptDetail,
|
||||
InterceptPending,
|
||||
InterceptPendingSummary,
|
||||
InterceptRule,
|
||||
JudgeConfig,
|
||||
JudgeUsage,
|
||||
@@ -1668,7 +1670,17 @@ export const api = {
|
||||
post<{ ok: boolean; enabled: boolean }>(`/asset-intercept/rules/${id}/toggle`, { enabled }),
|
||||
|
||||
// ---- intercept pending (ask) ----
|
||||
interceptPending: () => get<{ pending: InterceptPending[] }>("/intercept/pending").then((r) => arr(r.pending)),
|
||||
interceptPending: (taskId?: string) =>
|
||||
get<{ pending: InterceptPending[] }>(
|
||||
taskId ? `/intercept/pending?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending",
|
||||
).then((r) => arr(r.pending)),
|
||||
interceptPendingSummary: (taskId?: string): Promise<InterceptPendingSummary> =>
|
||||
get<{ count?: number; agent_names?: string[] }>(
|
||||
taskId ? `/intercept/pending/summary?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending/summary",
|
||||
).then((r) => ({
|
||||
count: r.count ?? 0,
|
||||
agent_names: arr(r.agent_names),
|
||||
})),
|
||||
interceptGetOne: (id: number) => get<InterceptPending>(`/intercept/pending/${id}`),
|
||||
interceptDecide: (id: number, decision: "allowed" | "denied") =>
|
||||
post<{ ok: boolean }>(`/intercept/pending/${id}/decide`, { decision }),
|
||||
@@ -1678,21 +1690,38 @@ export const api = {
|
||||
),
|
||||
interceptDetail: (id: number) => get<InterceptDetail>(`/intercept/history/${id}`),
|
||||
interceptHistory: () => get<{ items: InterceptApprovalRow[] }>("/intercept/history").then((r) => arr(r.items)),
|
||||
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
|
||||
get<{ items: InterceptApprovalRow[]; total?: number }>(
|
||||
`/intercept/history?${interceptPageQuery(page, size, filter)}`,
|
||||
).then((r) => ({
|
||||
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}): Promise<InterceptApprovalPage> =>
|
||||
get<{
|
||||
items: InterceptApprovalRow[];
|
||||
total?: number;
|
||||
total_approximate?: boolean;
|
||||
total_capped?: boolean;
|
||||
has_more?: boolean;
|
||||
}>(`/intercept/history?${interceptPageQuery(page, size, filter)}`).then((r) => ({
|
||||
items: arr(r.items),
|
||||
total: r.total ?? r.items?.length ?? 0,
|
||||
total_approximate: Boolean(r.total_approximate),
|
||||
total_capped: Boolean(r.total_capped),
|
||||
has_more: Boolean(r.has_more),
|
||||
})),
|
||||
interceptTask: (taskId: string) =>
|
||||
get<{ items: InterceptApprovalRow[] }>(`/intercept/task/${taskId}`).then((r) => arr(r.items)),
|
||||
interceptTaskPage: (taskId: string, page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
|
||||
get<{ items: InterceptApprovalRow[]; total?: number }>(
|
||||
`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`,
|
||||
).then((r) => ({
|
||||
interceptTaskPage: (
|
||||
taskId: string,
|
||||
page = 1,
|
||||
size = 20,
|
||||
filter: InterceptApprovalFilter = {},
|
||||
): Promise<InterceptApprovalPage> =>
|
||||
get<{
|
||||
items: InterceptApprovalRow[];
|
||||
total?: number;
|
||||
total_approximate?: boolean;
|
||||
total_capped?: boolean;
|
||||
has_more?: boolean;
|
||||
}>(`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`).then((r) => ({
|
||||
items: arr(r.items),
|
||||
total: r.total ?? r.items?.length ?? 0,
|
||||
total_approximate: Boolean(r.total_approximate),
|
||||
total_capped: Boolean(r.total_capped),
|
||||
has_more: Boolean(r.has_more),
|
||||
})),
|
||||
|
||||
// ---- intercept tool-config (全局工具拦截范围) ----
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2774,8 +2774,19 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (path === "/intercept/rules" && m === "GET") return { rules: D.interceptRules };
|
||||
if (seg[0] === "intercept" && seg[1] === "rules" && seg[3] === "toggle")
|
||||
return { ok: true, enabled: b.enabled ?? true };
|
||||
if (path === "/intercept/pending" && m === "GET")
|
||||
return { pending: mockInterceptHistory.filter((r) => r.status === "pending") };
|
||||
if (path === "/intercept/pending/summary" && m === "GET") {
|
||||
const taskId = q.get("task_id")?.trim() || "";
|
||||
const pending = mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId));
|
||||
if (!taskId) return { count: pending.length };
|
||||
const agentNames = [...new Set(pending.map((r) => r.agent_name).filter(Boolean))].sort();
|
||||
return { count: pending.length, agent_names: agentNames };
|
||||
}
|
||||
if (path === "/intercept/pending" && m === "GET") {
|
||||
const taskId = q.get("task_id")?.trim() || "";
|
||||
return {
|
||||
pending: mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId)),
|
||||
};
|
||||
}
|
||||
if (seg[0] === "intercept" && seg[1] === "pending" && seg[3] === "decide") {
|
||||
const id = Number(seg[2]);
|
||||
const row = mockInterceptHistory.find((r) => r.id === id) ?? mockInterceptPending.find((r) => r.id === id);
|
||||
@@ -2834,14 +2845,17 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
(search.startsWith("#") ? row.id === Number(search.slice(1)) : haystack.includes(search.toLowerCase())))
|
||||
);
|
||||
});
|
||||
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to)
|
||||
return { items: filtered, total: filtered.length };
|
||||
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to) {
|
||||
const capped = filtered.slice(0, 200);
|
||||
return { items: capped, total: capped.length };
|
||||
}
|
||||
const page = Math.max(1, Number(q.get("page")) || 1);
|
||||
const size = Math.min(100, Math.max(1, Number(q.get("size")) || 20));
|
||||
const offset = (page - 1) * size;
|
||||
return {
|
||||
items: filtered.slice(offset, offset + size),
|
||||
total: filtered.length,
|
||||
has_more: offset + size < filtered.length,
|
||||
page,
|
||||
page_size: size,
|
||||
};
|
||||
|
||||
+17
-4
@@ -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.
|
||||
@@ -1468,6 +1468,11 @@ export interface InterceptPending {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface InterceptPendingSummary {
|
||||
count: number;
|
||||
agent_names: string[];
|
||||
}
|
||||
|
||||
// JudgeConfig: 模型兜底审批(仅当没有任何拦截规则命中时由模型判断)的全局配置。
|
||||
export interface JudgeConfig {
|
||||
enabled: boolean;
|
||||
@@ -1514,6 +1519,14 @@ export interface InterceptApprovalRow extends InterceptPending {
|
||||
rule_name: string; // "" if rule was deleted
|
||||
}
|
||||
|
||||
export interface InterceptApprovalPage {
|
||||
items: InterceptApprovalRow[];
|
||||
total: number;
|
||||
total_approximate?: boolean;
|
||||
total_capped?: boolean;
|
||||
has_more?: boolean;
|
||||
}
|
||||
|
||||
// ── 资产同步 (ScopeSentry 数据源) ──────────────────────────────────────────────
|
||||
export interface SSProject {
|
||||
id: string; // MongoDB ObjectID — used as filter.project
|
||||
|
||||
Reference in new issue
Block a user