ci / go (push) Waiting to run
ci / go-db (agent) (push) Waiting to run
ci / go-db (config) (push) Waiting to run
ci / go-db (db) (push) Waiting to run
ci / go-db (evidence) (push) Waiting to run
ci / go-db (llmrec) (push) Waiting to run
ci / go-db (server) (push) Waiting to run
web / web (push) Waiting to run
docs / links (push) Canceled after 0s
detections / detections (push) Canceled after 0s
561 lines
16 KiB
Go
561 lines
16 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/Autumn-27/artex/db"
|
|
"github.com/Autumn-27/artex/guard"
|
|
"github.com/Autumn-27/artex/intercept"
|
|
"github.com/Autumn-27/norma/llm"
|
|
)
|
|
|
|
// chatGuard returns a guard wired with the manager's interceptor, used for chat
|
|
// conversations. Called once per applyLLM so a new LLM config always gets a fresh guard.
|
|
func (s *Server) chatGuard() *guard.Guard {
|
|
return guard.NewWithInterceptor(s.m.interceptor)
|
|
}
|
|
|
|
// 사용자에게 노출되는 판정(judge) 모델 오류 메시지(한국어). 이 오류는
|
|
// intercept.Judge 가 msgModelApprovalFailed 로 감싸 Decision.Message 로 노출하므로,
|
|
// 래퍼(intercept 패키지)와 언어가 어긋나지 않게 함께 한국어로 둔다.
|
|
const (
|
|
errNoJudgeModel = "사용할 수 있는 판정 모델이 설정되지 않았습니다"
|
|
errJudgeModelUnavailable = "%d번 판정 모델 프로필을 사용할 수 없습니다"
|
|
errJudgeVerdictMalformed = "모델 판정 형식이 올바르지 않습니다. 판정·실제 동작·성공 후 결과·적중 규칙을 모두 포함해야 합니다"
|
|
)
|
|
|
|
// wireInterceptReviewer installs the LLM fallback judge into the interceptor. The
|
|
// judge runs only on tool calls that matched no rule (see intercept.Judge). It
|
|
// resolves the configured judge profile (0 → active/default), builds a provider,
|
|
// runs a one-shot JSON classification with an explanation for every verdict.
|
|
func (s *Server) wireInterceptReviewer() {
|
|
s.m.interceptor.SetReviewer(func(ctx context.Context, profileID int64, prompt string, input intercept.ReviewInput) (intercept.Decision, error) {
|
|
if profileID == 0 {
|
|
if p, err := s.m.pg.ActiveProfile(); err == nil && p != nil {
|
|
profileID = p.ID
|
|
}
|
|
}
|
|
if profileID == 0 {
|
|
return intercept.Decision{}, errors.New(errNoJudgeModel)
|
|
}
|
|
prov, _, ok := s.providerForProfile(profileID)
|
|
if !ok {
|
|
return intercept.Decision{ProfileID: profileID}, fmt.Errorf(errJudgeModelUnavailable, profileID)
|
|
}
|
|
text, err := reviewCompletion(ctx, prov, prompt, input)
|
|
if err != nil {
|
|
return intercept.Decision{ProfileID: profileID}, err
|
|
}
|
|
v := intercept.ParseVerdict(text)
|
|
if v.Action == "" {
|
|
return intercept.Decision{ProfileID: profileID}, errors.New(errJudgeVerdictMalformed)
|
|
}
|
|
return intercept.Decision{Action: v.Action, Message: v.Reason, ProfileID: profileID}, nil
|
|
})
|
|
}
|
|
|
|
func reviewCompletion(ctx context.Context, prov llm.Provider, prompt string, input intercept.ReviewInput) (string, error) {
|
|
user, err := json.Marshal(input)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return streamCollectText(ctx, prov, prompt, string(user))
|
|
}
|
|
|
|
// streamCollectText runs a single non-streaming-style completion (thinking off,
|
|
// low temperature, bounded output) and returns the concatenated text. The
|
|
// budget includes the explanation and complete closing JSON delimiters.
|
|
func streamCollectText(ctx context.Context, prov llm.Provider, system, user string) (string, error) {
|
|
temp := 0.0
|
|
req := llm.CompletionRequest{
|
|
System: []string{system},
|
|
Messages: []llm.Message{llm.UserText(user)},
|
|
MaxTokens: 1024,
|
|
Temperature: &temp,
|
|
Thinking: "disabled",
|
|
}
|
|
var sb strings.Builder
|
|
for ev, err := range prov.Stream(ctx, req) {
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if ev.Type == llm.SETextDelta {
|
|
sb.WriteString(ev.Text)
|
|
}
|
|
}
|
|
return sb.String(), nil
|
|
}
|
|
|
|
// --- intercept rule CRUD ---
|
|
|
|
func (s *Server) interceptListRules(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
rules, err := pg.ListInterceptRules()
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if rules == nil {
|
|
rules = []db.InterceptRule{}
|
|
}
|
|
writeJSON(w, 200, map[string]any{"rules": rules})
|
|
}
|
|
|
|
func (s *Server) interceptCreateRule(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
var req interceptRuleReq
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if err := validateInterceptRuleReq(req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
rule, err := pg.CreateInterceptRule(req.Name, req.MatchTarget, req.MatchType, req.Pattern, req.Action, req.Message, req.Priority, req.Enabled, req.TimeoutEnabled, req.TimeoutSeconds, req.TimeoutAction)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
s.m.interceptor.Invalidate()
|
|
writeJSON(w, 200, rule)
|
|
}
|
|
|
|
func (s *Server) interceptUpdateRule(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok {
|
|
writeErr(w, 400, "bad rule id")
|
|
return
|
|
}
|
|
var req interceptRuleReq
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if err := validateInterceptRuleReq(req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
rule, err := pg.UpdateInterceptRule(id, req.Name, req.MatchTarget, req.MatchType, req.Pattern, req.Action, req.Message, req.Priority, req.Enabled, req.TimeoutEnabled, req.TimeoutSeconds, req.TimeoutAction)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
s.m.interceptor.Invalidate()
|
|
writeJSON(w, 200, rule)
|
|
}
|
|
|
|
func (s *Server) interceptDeleteRule(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok {
|
|
writeErr(w, 400, "bad rule id")
|
|
return
|
|
}
|
|
if err := pg.DeleteInterceptRule(id); err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
s.m.interceptor.Invalidate()
|
|
writeJSON(w, 200, map[string]any{"deleted": id})
|
|
}
|
|
|
|
func (s *Server) interceptToggleRule(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok {
|
|
writeErr(w, 400, "bad rule id")
|
|
return
|
|
}
|
|
var req struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if err := pg.ToggleInterceptRule(id, req.Enabled); err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
s.m.interceptor.Invalidate()
|
|
writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled})
|
|
}
|
|
|
|
// --- pending (ask) ---
|
|
|
|
func (s *Server) interceptListPending(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
pending, err := pg.ListPendingIntercepts()
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if pending == nil {
|
|
pending = []db.InterceptPending{}
|
|
}
|
|
writeJSON(w, 200, map[string]any{"pending": pending})
|
|
}
|
|
|
|
func (s *Server) interceptGetOne(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok {
|
|
writeErr(w, 400, "bad pending id")
|
|
return
|
|
}
|
|
p, err := pg.GetInterceptPending(id)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if p == nil {
|
|
writeErr(w, 404, "not found")
|
|
return
|
|
}
|
|
writeJSON(w, 200, p)
|
|
}
|
|
|
|
func (s *Server) interceptListTaskItems(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
taskID := r.PathValue("taskID")
|
|
if taskID == "" {
|
|
writeErr(w, 400, "bad task id")
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
filter, err := interceptFilterParams(q)
|
|
if err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if q.Get("page") == "" && q.Get("size") == "" && filter == (db.InterceptApprovalFilter{}) {
|
|
items, err := pg.ListTaskIntercepts(taskID)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if items == nil {
|
|
items = []db.InterceptApprovalRow{}
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": items, "total": len(items)})
|
|
return
|
|
}
|
|
page, size := interceptPageParams(q)
|
|
items, total, 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})
|
|
}
|
|
|
|
func (s *Server) interceptHistory(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
q := r.URL.Query()
|
|
filter, err := interceptFilterParams(q)
|
|
if err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if q.Get("page") == "" && q.Get("size") == "" && filter == (db.InterceptApprovalFilter{}) {
|
|
items, err := pg.ListAllIntercepts(200)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if items == nil {
|
|
items = []db.InterceptApprovalRow{}
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": items, "total": len(items)})
|
|
return
|
|
}
|
|
page, size := interceptPageParams(q)
|
|
items, total, err := pg.ListAllInterceptsPage(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})
|
|
}
|
|
|
|
func interceptFilterParams(q url.Values) (db.InterceptApprovalFilter, error) {
|
|
filter := db.InterceptApprovalFilter{Status: q.Get("status"), DecisionSource: q.Get("decision_source")}
|
|
switch filter.Status {
|
|
case "", "pending", "allowed", "denied", "timeout":
|
|
default:
|
|
return filter, fmt.Errorf("status 값은 pending, allowed, denied, timeout 중 하나여야 합니다")
|
|
}
|
|
switch filter.DecisionSource {
|
|
case "", "model", "rule", "unknown":
|
|
default:
|
|
return filter, fmt.Errorf("decision_source 값은 model, rule, unknown 중 하나여야 합니다")
|
|
}
|
|
return filter, nil
|
|
}
|
|
|
|
func interceptPageParams(q url.Values) (int, int) {
|
|
page := atoiDefault(q.Get("page"), 1)
|
|
size := atoiDefault(q.Get("size"), 20)
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if size < 1 {
|
|
size = 20
|
|
}
|
|
if size > 100 {
|
|
size = 100
|
|
}
|
|
return page, size
|
|
}
|
|
|
|
func (s *Server) interceptDecide(w http.ResponseWriter, r *http.Request) {
|
|
id, ok := pathInt(r, "id")
|
|
if !ok {
|
|
writeErr(w, 400, "bad pending id")
|
|
return
|
|
}
|
|
var req struct {
|
|
Decision string `json:"decision"` // "allowed" | "denied"
|
|
}
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if req.Decision != "allowed" && req.Decision != "denied" {
|
|
writeErr(w, 400, "decision 값은 allowed 또는 denied 중 하나여야 합니다")
|
|
return
|
|
}
|
|
if err := s.m.interceptor.Decide(id, req.Decision == "allowed"); err != nil {
|
|
if errors.Is(err, intercept.ErrAlreadyDecided) {
|
|
writeErr(w, 409, err.Error())
|
|
return
|
|
}
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true})
|
|
}
|
|
|
|
// --- tool-config (全局工具拦截范围) ---
|
|
|
|
// interceptGetToolConfig returns the list of tool names that are currently
|
|
// configured to enter the intercept rule system.
|
|
func (s *Server) interceptGetToolConfig(w http.ResponseWriter, r *http.Request) {
|
|
tools, err := s.m.interceptor.GetEnabledTools()
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"enabled_tools": tools})
|
|
}
|
|
|
|
// interceptSetToolConfig replaces the list of tool names that should enter
|
|
// the intercept rule system.
|
|
func (s *Server) interceptSetToolConfig(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
EnabledTools []string `json:"enabled_tools"`
|
|
}
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
if req.EnabledTools == nil {
|
|
req.EnabledTools = []string{}
|
|
}
|
|
if err := s.m.interceptor.SetEnabledTools(req.EnabledTools); err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true})
|
|
}
|
|
|
|
// --- LLM fallback judge config (全局模型兜底) ---
|
|
|
|
// interceptGetJudgeConfig returns the resolved judge configuration. Prompt is the
|
|
// effective prompt (built-in template when unset), so the UI can prefill it.
|
|
func (s *Server) interceptGetJudgeConfig(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, 200, s.m.interceptor.GetJudgeConfig())
|
|
}
|
|
|
|
// interceptSetJudgeConfig persists the judge configuration.
|
|
func (s *Server) interceptSetJudgeConfig(w http.ResponseWriter, r *http.Request) {
|
|
var req intercept.JudgeConfig
|
|
if err := decode(r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
switch req.FailAction {
|
|
case "allow", "ask", "deny":
|
|
default:
|
|
writeErr(w, 400, "fail_action 값은 allow, ask, deny 중 하나여야 합니다")
|
|
return
|
|
}
|
|
switch req.AskTimeoutAction {
|
|
case "allow", "deny":
|
|
default:
|
|
writeErr(w, 400, "ask_timeout_action 값은 allow 또는 deny 중 하나여야 합니다")
|
|
return
|
|
}
|
|
if err := s.m.interceptor.SetJudgeConfig(req); err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true})
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
type interceptRuleReq struct {
|
|
Name string `json:"name"`
|
|
Enabled bool `json:"enabled"`
|
|
Priority int `json:"priority"`
|
|
MatchTarget string `json:"match_target"`
|
|
MatchType string `json:"match_type"`
|
|
Pattern string `json:"pattern"`
|
|
Action string `json:"action"`
|
|
Message string `json:"message"`
|
|
TimeoutEnabled bool `json:"timeout_enabled"`
|
|
TimeoutSeconds int `json:"timeout_seconds"`
|
|
TimeoutAction string `json:"timeout_action"`
|
|
}
|
|
|
|
func validateInterceptRuleReq(req interceptRuleReq) error {
|
|
if req.Name == "" {
|
|
return fmt.Errorf("name 값은 비워 둘 수 없습니다")
|
|
}
|
|
switch req.MatchTarget {
|
|
case "tool_name", "tool_input":
|
|
default:
|
|
return fmt.Errorf("match_target 값은 tool_name 또는 tool_input 중 하나여야 합니다")
|
|
}
|
|
switch req.MatchType {
|
|
case "string", "regex":
|
|
default:
|
|
return fmt.Errorf("match_type 값은 string 또는 regex 중 하나여야 합니다")
|
|
}
|
|
if req.Pattern == "" {
|
|
return fmt.Errorf("pattern 값은 비워 둘 수 없습니다")
|
|
}
|
|
switch req.Action {
|
|
case "allow", "deny", "ask":
|
|
default:
|
|
return fmt.Errorf("action 값은 allow, deny, ask 중 하나여야 합니다")
|
|
}
|
|
if req.MatchType == "regex" {
|
|
if _, err := regexp.Compile(req.Pattern); err != nil {
|
|
return fmt.Errorf("pattern 값이 올바른 정규식이 아닙니다: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) interceptDetail(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok || id <= 0 {
|
|
writeErr(w, 400, "bad approval id")
|
|
return
|
|
}
|
|
detail, err := pg.GetInterceptDetail(id)
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if detail == nil {
|
|
writeErr(w, 404, "not found")
|
|
return
|
|
}
|
|
writeJSON(w, 200, detail)
|
|
}
|
|
|
|
// The navigation endpoint returns only the original call and its paired result.
|
|
func (s *Server) interceptExecution(w http.ResponseWriter, r *http.Request) {
|
|
pg := s.pg(w)
|
|
if pg == nil {
|
|
return
|
|
}
|
|
id, ok := pathInt(r, "id")
|
|
if !ok || id <= 0 {
|
|
writeErr(w, 400, "bad approval id")
|
|
return
|
|
}
|
|
target, err := pg.GetInterceptExecution(id)
|
|
if errors.Is(err, db.ErrInterceptTaskDeleted) || errors.Is(err, db.ErrInterceptSessionDeleted) {
|
|
writeErr(w, http.StatusGone, err.Error())
|
|
return
|
|
}
|
|
if errors.Is(err, db.ErrInterceptExecutionUnavailable) {
|
|
writeErr(w, 409, err.Error())
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeErr(w, 500, err.Error())
|
|
return
|
|
}
|
|
if target == nil {
|
|
// Conversation deletion cascades approval rows. A stale source link still
|
|
// carries its conversation ID, allowing a precise message without retaining
|
|
// deleted conversations or changing their deletion semantics.
|
|
if convID, parseErr := strconv.ParseInt(r.URL.Query().Get("conversation"), 10, 64); parseErr == nil && convID > 0 {
|
|
conv, getErr := pg.GetConversation(convID)
|
|
if getErr != nil {
|
|
writeErr(w, 500, getErr.Error())
|
|
return
|
|
}
|
|
if conv == nil {
|
|
writeErr(w, http.StatusGone, "대화가 이미 삭제되었습니다")
|
|
return
|
|
}
|
|
}
|
|
writeErr(w, 404, "승인 기록이 삭제되었거나 존재하지 않습니다")
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"conversation_id": target.ConversationID, "task_id": target.TaskID, "session": target.Session, "seq": target.Seq, "items": activityDTOs(target.Items)})
|
|
}
|