mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-06 21:11:50 +08:00
feat: add optional task intelligence recording and views
This commit is contained in:
1 parent
e66789633a
commit
d70dd15e11
24 files changed
+1537
-40
No files matched your search
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"path/filepath"
|
||||
@@ -211,6 +212,17 @@ func seedPrompts(pg *db.DB) {
|
||||
// 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, 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, false) {
|
||||
return 0, fmt.Errorf("任务情报自动记录已关闭")
|
||||
}
|
||||
item, err := pg.RecordIntelligence(ctx, taskID, nodeID, worker, input)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return item.ID, nil
|
||||
}
|
||||
// Seed the built-in domain tools (first-insert only; DO NOTHING preserves edits).
|
||||
// No startup prune: rows we didn't seed are left alone so future user-defined
|
||||
// custom tools (system=false, added via the UI) survive restarts.
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func intelligenceError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, db.ErrIntelligenceInvalid):
|
||||
writeErr(w, 400, err.Error())
|
||||
case errors.Is(err, db.ErrIntelligenceNotFound):
|
||||
writeErr(w, 404, "情报不存在或不属于当前范围")
|
||||
default:
|
||||
writeErr(w, 500, err.Error())
|
||||
}
|
||||
}
|
||||
func (s *Server) intelligenceFilter(w http.ResponseWriter, r *http.Request) (db.IntelligenceFilter, bool) {
|
||||
f := db.IntelligenceFilter{}
|
||||
id, ok := pathInt(r, "id")
|
||||
if !ok || id <= 0 {
|
||||
writeErr(w, 400, "无效 ID")
|
||||
return f, false
|
||||
}
|
||||
if r.PathValue("scope") == "assets" {
|
||||
f.AssetID = id
|
||||
} else {
|
||||
f.TaskID = id
|
||||
}
|
||||
var exists bool
|
||||
var err error
|
||||
if f.TaskID > 0 {
|
||||
err = s.m.pg.QueryRowContext(r.Context(), `SELECT EXISTS(SELECT 1 FROM tasks WHERE id=$1 AND deleted_at IS NULL)`, id).Scan(&exists)
|
||||
} else {
|
||||
err = s.m.pg.QueryRowContext(r.Context(), `SELECT EXISTS(SELECT 1 FROM assets WHERE id=$1)`, id).Scan(&exists)
|
||||
}
|
||||
if err != nil {
|
||||
intelligenceError(w, err)
|
||||
return f, false
|
||||
}
|
||||
if !exists {
|
||||
writeErr(w, 404, "任务或资产不存在")
|
||||
return f, false
|
||||
}
|
||||
q := r.URL.Query()
|
||||
f.Kind = q.Get("kind")
|
||||
f.Status = q.Get("status")
|
||||
f.Query = q.Get("q")
|
||||
f.Limit, _ = strconv.Atoi(q.Get("limit"))
|
||||
f.Offset, _ = strconv.Atoi(q.Get("offset"))
|
||||
if len(f.Query) > 500 {
|
||||
writeErr(w, 400, "搜索关键词过长")
|
||||
return f, false
|
||||
}
|
||||
return f, true
|
||||
}
|
||||
func (s *Server) listIntelligence(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := s.intelligenceFilter(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := s.m.pg.ListIntelligence(r.Context(), f)
|
||||
if err != nil {
|
||||
intelligenceError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, page)
|
||||
}
|
||||
func (s *Server) getIntelligence(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := s.intelligenceFilter(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := pathInt(r, "intelID")
|
||||
if !ok {
|
||||
writeErr(w, 400, "无效情报 ID")
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.GetIntelligence(r.Context(), id)
|
||||
if err != nil {
|
||||
intelligenceError(w, err)
|
||||
return
|
||||
}
|
||||
allowed := false
|
||||
if f.TaskID > 0 {
|
||||
err = s.m.pg.QueryRowContext(r.Context(), `SELECT $1::bigint=$2::bigint OR EXISTS(SELECT 1 FROM task_relations WHERE task_id=$1 AND source_task_id=$2)`, f.TaskID, item.TaskID).Scan(&allowed)
|
||||
} else {
|
||||
for _, assetID := range item.AssetIDs {
|
||||
if assetID == f.AssetID {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
intelligenceError(w, err)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
intelligenceError(w, db.ErrIntelligenceNotFound)
|
||||
return
|
||||
}
|
||||
item.Inherited = f.TaskID > 0 && item.TaskID != f.TaskID
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, 200, item)
|
||||
}
|
||||
func (s *Server) updateIntelligence(w http.ResponseWriter, r *http.Request) {
|
||||
taskID, ok := pathInt(r, "id")
|
||||
if !ok {
|
||||
writeErr(w, 400, "无效任务 ID")
|
||||
return
|
||||
}
|
||||
id, ok := pathInt(r, "intelID")
|
||||
if !ok {
|
||||
writeErr(w, 400, "无效情报 ID")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
var req struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, "无效请求")
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.UpdateIntelligenceStatus(r.Context(), taskID, id, req.Status); err != nil {
|
||||
intelligenceError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]bool{"updated": true})
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIntelligenceHTTPSettingsAndScope(t *testing.T) {
|
||||
s, initial, request := trafficEvidenceServer(t)
|
||||
f, err := s.m.pg.GetFinding(initial.FindingID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskID := *f.TaskID
|
||||
if s.settingsPayload()[db.SettingTaskIntelligence] != false {
|
||||
t.Fatal("default must be off")
|
||||
}
|
||||
if r := request("PUT", "/api/settings", `{"task_intelligence_enabled":true}`); r.Code != 200 {
|
||||
t.Fatal(r.Code, r.Body)
|
||||
}
|
||||
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"}
|
||||
item, err := s.m.pg.RecordIntelligence(t.Context(), taskID, 0, "qa", in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := fmt.Sprintf("/api/tasks/%d/intelligence", taskID)
|
||||
r := request("GET", base, "")
|
||||
if r.Code != 200 || strings.Contains(r.Body.String(), in.Content) || strings.Contains(r.Body.String(), in.Evidence) {
|
||||
t.Fatalf("list leaked secret: %d %s", r.Code, r.Body)
|
||||
}
|
||||
r = request("GET", fmt.Sprintf("%s/%d", base, item.ID), "")
|
||||
if r.Code != 200 || !strings.Contains(r.Body.String(), in.Content) {
|
||||
t.Fatal("explicit reveal failed", r.Code, r.Body)
|
||||
}
|
||||
if r = request("PATCH", fmt.Sprintf("%s/%d", base, item.ID), `{"status":"verified"}`); r.Code != 200 {
|
||||
t.Fatal(r.Code, r.Body)
|
||||
}
|
||||
other, err := s.m.pg.CreateTask("unrelated intel API", "test", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.m.pg.DeleteTask(other.ID)
|
||||
for _, method := range []string{"GET", "PATCH"} {
|
||||
r = request(method, fmt.Sprintf("/api/tasks/%d/intelligence/%d", other.ID, item.ID), `{"status":"invalid"}`)
|
||||
if r.Code != 404 {
|
||||
t.Fatal("cross task access", method, r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
if _, err = s.m.pg.Exec(`INSERT INTO task_relations(task_id,source_task_id) VALUES($1,$2)`, other.ID, taskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r = request("GET", fmt.Sprintf("/api/tasks/%d/intelligence/%d", other.ID, item.ID), "")
|
||||
if r.Code != 200 {
|
||||
t.Fatal(r.Code, r.Body)
|
||||
}
|
||||
var got db.Intelligence
|
||||
if err = json.Unmarshal(r.Body.Bytes(), &got); err != nil || !got.Inherited {
|
||||
t.Fatal("missing inherited marker")
|
||||
}
|
||||
if r = request("PATCH", fmt.Sprintf("/api/tasks/%d/intelligence/%d", other.ID, item.ID), `{"status":"invalid"}`); r.Code != 404 {
|
||||
t.Fatal("inherited mutation accepted")
|
||||
}
|
||||
if r = request("PUT", "/api/settings", `{"task_intelligence_enabled":false}`); r.Code != 200 {
|
||||
t.Fatal(r.Code, r.Body)
|
||||
}
|
||||
if r = request("GET", base, ""); r.Code != 200 || !strings.Contains(r.Body.String(), `"total":1`) {
|
||||
t.Fatal("disable hid saved records")
|
||||
}
|
||||
}
|
||||
+32
-13
@@ -858,6 +858,17 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/llm/records/tasks", s.pgLLMTasks)
|
||||
mux.HandleFunc("GET /api/llm/records/by-model", s.pgTokenByModel) // 按模型聚合本任务 token 用量
|
||||
mux.HandleFunc("GET /api/llm/records/{id}", s.pgGetLLMRecord)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/intelligence", s.listIntelligence)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/intelligence/{intelID}", s.getIntelligence)
|
||||
mux.HandleFunc("PATCH /api/tasks/{id}/intelligence/{intelID}", s.updateIntelligence)
|
||||
mux.HandleFunc("GET /api/assets/{id}/intelligence", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.SetPathValue("scope", "assets")
|
||||
s.listIntelligence(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/assets/{id}/intelligence/{intelID}", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.SetPathValue("scope", "assets")
|
||||
s.getIntelligence(w, r)
|
||||
})
|
||||
mux.HandleFunc("GET /api/settings", s.getSettings)
|
||||
mux.HandleFunc("PUT /api/settings", s.putSettings)
|
||||
// 漏洞 IM 推送。渠道是「多实例 + 各自过滤规则」的资源,因此独立成一组
|
||||
@@ -3397,19 +3408,20 @@ func (s *Server) settingsPayload() map[string]any {
|
||||
concLimit = defaultConcurrencyLimit // 关闭时也回显一个合理默认值给 UI
|
||||
}
|
||||
return map[string]any{
|
||||
"traffic_capture": s.m.TrafficEnabled(),
|
||||
"agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, false),
|
||||
"llm_record": s.m.LLMRecordEnabled(),
|
||||
"web_search_enabled": on,
|
||||
"web_search_backend": backend,
|
||||
"brave_key_set": strings.TrimSpace(braveKey) != "",
|
||||
"tavily_key_set": strings.TrimSpace(tavilyKey) != "",
|
||||
"web_search_proxy": proxy, // 独立出口代理(http/https/socks5),空=直连
|
||||
"global_proxy": s.m.GlobalProxy(), // 全局出口代理(http/https/socks5),所有目标流量走它,空=直连
|
||||
"python_interpreter": strings.TrimSpace(pyStored), // 用户/自动设的值(空=用运行时检测)
|
||||
"workers": s.m.Workers(), // 并发工作 agent 数(默认3);对之后启动的任务生效
|
||||
"task_concurrency_enabled": concOn, // 任务并发上限开关(默认关)
|
||||
"task_concurrency_limit": concLimit, // 同时运行任务上限(开启后默认5)
|
||||
"traffic_capture": s.m.TrafficEnabled(),
|
||||
"agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, false),
|
||||
"task_intelligence_enabled": s.m.pg.GetBool(db.SettingTaskIntelligence, false),
|
||||
"llm_record": s.m.LLMRecordEnabled(),
|
||||
"web_search_enabled": on,
|
||||
"web_search_backend": backend,
|
||||
"brave_key_set": strings.TrimSpace(braveKey) != "",
|
||||
"tavily_key_set": strings.TrimSpace(tavilyKey) != "",
|
||||
"web_search_proxy": proxy, // 独立出口代理(http/https/socks5),空=直连
|
||||
"global_proxy": s.m.GlobalProxy(), // 全局出口代理(http/https/socks5),所有目标流量走它,空=直连
|
||||
"python_interpreter": strings.TrimSpace(pyStored), // 用户/自动设的值(空=用运行时检测)
|
||||
"workers": s.m.Workers(), // 并发工作 agent 数(默认3);对之后启动的任务生效
|
||||
"task_concurrency_enabled": concOn, // 任务并发上限开关(默认关)
|
||||
"task_concurrency_limit": concLimit, // 同时运行任务上限(开启后默认5)
|
||||
// LLM 轮询(故障转移)。默认关;开启后走全局激活配置的 agent 在当前配置不可用时
|
||||
// 自动切到下一个配置。bind_fallback 仅在轮询开启时有意义(默认关)。
|
||||
"llm_pool_enabled": s.m.LLMPoolEnabled(),
|
||||
@@ -3469,6 +3481,7 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
TrafficCapture *bool `json:"traffic_capture"`
|
||||
AgentTrafficBinding *bool `json:"agent_traffic_binding"`
|
||||
TaskIntelligence *bool `json:"task_intelligence_enabled"`
|
||||
LLMRecord *bool `json:"llm_record"` // LLM 录制开关(默认关);即时生效,无需重建 agent
|
||||
// Web search. WebSearchEnabled/Backend toggle the tool + backend; BraveKey/TavilyKey
|
||||
// are optional — omit (null) to leave a stored key untouched, send "" to clear.
|
||||
@@ -3611,6 +3624,12 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// built under the OLD switch state — drop them so they pick up the new one.
|
||||
s.invalidateProfileAgents()
|
||||
}
|
||||
if req.TaskIntelligence != nil {
|
||||
if err := s.m.pg.SetBool(db.SettingTaskIntelligence, *req.TaskIntelligence); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.AgentTrafficBinding != nil {
|
||||
if err := s.m.pg.SetBool(settingAgentTrafficBinding, *req.AgentTrafficBinding); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
|
||||
Reference in new issue
Block a user