mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-10-31 18:23:50 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0e25d766f | ||
|
|
0ed68d9143 | ||
|
|
542d7e9ca6 | ||
|
|
35a33b20f9 | ||
|
|
74d8b1efa2 | ||
|
|
92e58d3de7 | ||
|
|
21057b1a6b | ||
|
|
136782f48e | ||
|
|
3af131272c | ||
|
|
07c0c8ee35 |
No files matched your search
+15
-1
@@ -30,7 +30,10 @@ import (
|
||||
|
||||
// Config describes the LLM backend resolved from the environment.
|
||||
type Config struct {
|
||||
Format llm.Format
|
||||
Format llm.Format
|
||||
// Jev marks the TypeSafe System One judge protocol. It must never be sent
|
||||
// through the chat/completions provider path.
|
||||
Jev bool
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Model string
|
||||
@@ -204,6 +207,11 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config {
|
||||
Stream: true, // 默认流式;调用方按 profile 覆盖
|
||||
}
|
||||
switch strings.TrimSpace(provider) {
|
||||
case "jev":
|
||||
c.Jev = true
|
||||
if c.Model == "" {
|
||||
c.Model = "jev-latest"
|
||||
}
|
||||
case "openai":
|
||||
c.Format = llm.FormatOpenAI
|
||||
// provider appends "/chat/completions"; tolerate a full endpoint URL.
|
||||
@@ -241,6 +249,9 @@ func isFalsy(s string) bool {
|
||||
|
||||
// Provider returns the short provider name ("anthropic"/"openai").
|
||||
func (c Config) Provider() string {
|
||||
if c.Jev {
|
||||
return "jev"
|
||||
}
|
||||
switch c.Format {
|
||||
case llm.FormatOpenAI:
|
||||
return "openai"
|
||||
@@ -259,6 +270,9 @@ func (c Config) NewProvider() (llm.Provider, error) {
|
||||
// NewProviderWithLimiter reuses quota history across provider rebuilds. Callers
|
||||
// sharing a profile must retain the same limiter outside their provider cache.
|
||||
func (c Config) NewProviderWithLimiter(limiter *RequestLimiter) (llm.Provider, error) {
|
||||
if c.Jev {
|
||||
return nil, fmt.Errorf("Jev System One 仅可用于拦截判定模型,不能作为聊天 provider")
|
||||
}
|
||||
client, err := quotaAwareHTTPClient(c.Proxy, c.SessionHeaderKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package agent
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestJevConfigCannotBuildChatProvider(t *testing.T) {
|
||||
c := ConfigFrom("jev", "", "", "key", "")
|
||||
if !c.Jev || c.Provider() != "jev" {
|
||||
t.Fatalf("unexpected Jev config: %+v", c)
|
||||
}
|
||||
if _, err := c.NewProvider(); err == nil {
|
||||
t.Fatal("Jev config must be rejected by chat provider construction")
|
||||
}
|
||||
}
|
||||
+28
-2
@@ -139,7 +139,7 @@ func (d *DB) ProfileByID(id int64) (*LLMProfile, error) {
|
||||
// walk the slice front to back.
|
||||
func (d *DB) PoolProfiles() ([]*LLMProfile, error) {
|
||||
rows, err := d.Query(`SELECT ` + profileColsKey + ` FROM llm_profiles
|
||||
WHERE COALESCE(api_key,'') <> '' AND (is_default OR NOT pool_exclude)
|
||||
WHERE format <> 'jev' AND COALESCE(api_key,'') <> '' AND (is_default OR NOT pool_exclude)
|
||||
ORDER BY is_default DESC, priority DESC, id ASC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -158,6 +158,12 @@ ORDER BY is_default DESC, priority DESC, id ASC`)
|
||||
|
||||
// SaveProfile inserts (id==0) or updates a profile. Empty apiKey on update keeps existing.
|
||||
func (d *DB) SaveProfile(p *LLMProfile) (int64, error) {
|
||||
if p.Format == "jev" && p.ID != 0 {
|
||||
var active bool
|
||||
if err := d.QueryRow(`SELECT is_default FROM llm_profiles WHERE id=$1`, p.ID).Scan(&active); err == nil && active {
|
||||
return 0, ErrJevProfileJudgeOnly
|
||||
}
|
||||
}
|
||||
hint := p.APIKeyHint
|
||||
if len(p.APIKey) >= 4 {
|
||||
hint = "…" + p.APIKey[len(p.APIKey)-4:]
|
||||
@@ -187,6 +193,7 @@ var (
|
||||
ErrActiveLLMProfileDelete = errors.New("cannot delete the active LLM profile; activate another profile first")
|
||||
ErrLLMProfileReferencesChanged = errors.New("LLM profile references changed while deleting; retry the request")
|
||||
ErrLLMProfileNotFound = errors.New("LLM profile not found")
|
||||
ErrJevProfileJudgeOnly = errors.New("Jev System One 配置仅可用于拦截判定模型,不能用于对话或任务")
|
||||
)
|
||||
|
||||
func (d *DB) DeleteProfile(id int64) error {
|
||||
@@ -422,6 +429,16 @@ func (d *DB) SetActiveProfile(id int64) error {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var format string
|
||||
if err := tx.QueryRow(`SELECT format FROM llm_profiles WHERE id=$1 FOR KEY SHARE`, id).Scan(&format); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return ErrLLMProfileNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if format == "jev" {
|
||||
return ErrJevProfileJudgeOnly
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE llm_profiles SET is_default=false WHERE is_default`); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -613,6 +630,15 @@ func (d *DB) SetAgentLLMProfile(key string, id *int64) error {
|
||||
if err := lockLLMProfileForReference(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if id != nil {
|
||||
var format string
|
||||
if err := tx.QueryRow(`SELECT format FROM llm_profiles WHERE id=$1`, *id).Scan(&format); err != nil {
|
||||
return err
|
||||
}
|
||||
if format == "jev" {
|
||||
return ErrJevProfileJudgeOnly
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE agents SET llm_profile_id=$1 WHERE id=$2`, id, agentID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -815,7 +841,7 @@ type MCPServer struct {
|
||||
Env json.RawMessage `json:"env"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Insecure bool `json:"insecure"` // http: skip TLS cert verification (self-signed servers, issue #108)
|
||||
Insecure bool `json:"insecure"` // http: skip TLS cert verification (self-signed servers, issue #108)
|
||||
Tools []string `json:"tools,omitempty"` // cached tool names (mcp_tools_cache)
|
||||
}
|
||||
|
||||
|
||||
@@ -183,6 +183,25 @@ func TestConfigStores(t *testing.T) {
|
||||
d.DeleteMCP(mid)
|
||||
}
|
||||
|
||||
func TestJevProfileCannotBeActivatedOrAgentBound(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
id, err := d.SaveProfile(&LLMProfile{Name: "t-jev-only", Format: "jev", Model: "jev-latest", APIKey: "jev-key"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id) })
|
||||
if err := d.SetActiveProfile(id); !errors.Is(err, ErrJevProfileJudgeOnly) {
|
||||
t.Fatalf("activate Jev error=%v, want %v", err, ErrJevProfileJudgeOnly)
|
||||
}
|
||||
if err := d.SetAgentLLMProfile("planner", &id); !errors.Is(err, ErrJevProfileJudgeOnly) {
|
||||
t.Fatalf("bind Jev error=%v, want %v", err, ErrJevProfileJudgeOnly)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (indexOf(s, sub) >= 0)
|
||||
}
|
||||
|
||||
+5
-1
@@ -705,7 +705,11 @@ func (d *DB) ResolveFindingReportConversation(findingID int64) (*int64, error) {
|
||||
a.detail ILIKE '%finding_id=' || $1::text || '%' OR
|
||||
a.detail ILIKE '%"finding_id":' || $1::text || '%'
|
||||
)
|
||||
ORDER BY c.updated_at DESC, c.id DESC LIMIT 1`, findingID).Scan(&id)
|
||||
ORDER BY CASE WHEN EXISTS (
|
||||
SELECT 1 FROM conversation_activities r
|
||||
WHERE r.conversation_id=c.id AND (r.tool='update_finding_report' OR r.summary ILIKE 'finding % report updated%')
|
||||
) THEN 0 ELSE 1 END,
|
||||
c.created_at ASC, c.id ASC LIMIT 1`, findingID).Scan(&id)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
+3
-3
@@ -362,7 +362,7 @@ CREATE TABLE IF NOT EXISTS settings (
|
||||
CREATE TABLE IF NOT EXISTS llm_profiles (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses')),
|
||||
format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','jev')),
|
||||
base_url TEXT,
|
||||
proxy TEXT,
|
||||
model TEXT NOT NULL,
|
||||
@@ -415,11 +415,11 @@ ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS priority INTEGER NOT NULL
|
||||
ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS pool_exclude BOOLEAN NOT NULL DEFAULT false;
|
||||
-- 流式开关;补旧库。默认 true = 保持既有的流式行为,旧配置无感升级。
|
||||
ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS streaming BOOLEAN NOT NULL DEFAULT true;
|
||||
-- 放开 format 约束以容纳 openai-responses(OpenAI Responses API);补旧库。
|
||||
-- 放开 format 约束以容纳 openai-responses(OpenAI Responses API)和 Jev System One;补旧库。
|
||||
-- 每次启动执行,幂等:先删旧 CHECK 再建含三值的新 CHECK。
|
||||
ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check;
|
||||
ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check
|
||||
CHECK (format IN ('openai','anthropic','openai-responses'));
|
||||
CHECK (format IN ('openai','anthropic','openai-responses','jev'));
|
||||
|
||||
-- 输出上限及其字段名;补旧库。默认 0 / '' = 不发送上限、沿用 max_tokens 字段名,
|
||||
-- 旧配置行为完全不变。
|
||||
|
||||
+35
-10
@@ -311,6 +311,7 @@ const (
|
||||
settingJudgeAskTimeoutSecs = "llm_judge_ask_timeout_seconds"
|
||||
settingJudgeAskTimeoutAction = "llm_judge_ask_timeout_action"
|
||||
settingJudgeIncompleteScript = "llm_judge_incomplete_script_action"
|
||||
settingJudgeConfidence = "llm_judge_confidence_threshold"
|
||||
)
|
||||
|
||||
// Judge default values.
|
||||
@@ -320,6 +321,7 @@ const (
|
||||
defaultJudgeFailAction = "ask"
|
||||
defaultJudgeAskTimeoutSecs = 300
|
||||
defaultJudgeAskTimeoutAction = "deny"
|
||||
defaultJudgeConfidence = 0.55
|
||||
// DefaultIncompleteScriptAction keeps incomplete snapshots with the judge.
|
||||
DefaultIncompleteScriptAction = "model"
|
||||
)
|
||||
@@ -327,16 +329,17 @@ const (
|
||||
// JudgeConfig is the resolved LLM-fallback-judge configuration. Prompt is always
|
||||
// non-empty (falls back to DefaultJudgePrompt).
|
||||
type JudgeConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ProfileID int64 `json:"profile_id"` // 0 = follow active/default
|
||||
Prompt string `json:"prompt"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"` // per attempt
|
||||
RetryCount int `json:"retry_count"` // additional attempts; 0 = disabled
|
||||
RetryIntervalMS int `json:"retry_interval_ms"`
|
||||
FailAction string `json:"fail_action"` // allow|ask|deny
|
||||
AskTimeoutSeconds int `json:"ask_timeout_seconds"`
|
||||
AskTimeoutAction string `json:"ask_timeout_action"` // allow|deny
|
||||
IncompleteScriptAction string `json:"incomplete_script_action"` // ask|model
|
||||
Enabled bool `json:"enabled"`
|
||||
ProfileID int64 `json:"profile_id"` // 0 = follow active/default
|
||||
Prompt string `json:"prompt"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"` // per attempt
|
||||
RetryCount int `json:"retry_count"` // additional attempts; 0 = disabled
|
||||
RetryIntervalMS int `json:"retry_interval_ms"`
|
||||
FailAction string `json:"fail_action"` // allow|ask|deny
|
||||
AskTimeoutSeconds int `json:"ask_timeout_seconds"`
|
||||
AskTimeoutAction string `json:"ask_timeout_action"` // allow|deny
|
||||
IncompleteScriptAction string `json:"incomplete_script_action"` // ask|model
|
||||
ConfidenceThreshold float64 `json:"confidence_threshold"` // Jev only; below this becomes ask
|
||||
}
|
||||
|
||||
// judgeConfig reads the judge configuration from settings, applying defaults for
|
||||
@@ -353,6 +356,7 @@ func (i *Interceptor) judgeConfig() JudgeConfig {
|
||||
AskTimeoutSeconds: i.getSettingInt(settingJudgeAskTimeoutSecs, defaultJudgeAskTimeoutSecs),
|
||||
AskTimeoutAction: i.getSettingChoice(settingJudgeAskTimeoutAction, defaultJudgeAskTimeoutAction, "allow", "deny"),
|
||||
IncompleteScriptAction: i.getSettingChoice(settingJudgeIncompleteScript, DefaultIncompleteScriptAction, "ask", "model"),
|
||||
ConfidenceThreshold: i.getSettingFloat(settingJudgeConfidence, defaultJudgeConfidence),
|
||||
}
|
||||
// Prompt: stored value if non-empty, else the built-in template.
|
||||
if v, ok, _ := i.db.GetSetting(settingJudgePrompt); ok && strings.TrimSpace(v) != "" {
|
||||
@@ -366,9 +370,24 @@ func (i *Interceptor) judgeConfig() JudgeConfig {
|
||||
if c.AskTimeoutSeconds <= 0 {
|
||||
c.AskTimeoutSeconds = defaultJudgeAskTimeoutSecs
|
||||
}
|
||||
if c.ConfidenceThreshold <= 0 || c.ConfidenceThreshold > 1 {
|
||||
c.ConfidenceThreshold = defaultJudgeConfidence
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (i *Interceptor) getSettingFloat(key string, def float64) float64 {
|
||||
v, ok, err := i.db.GetSetting(key)
|
||||
if err != nil || !ok {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (i *Interceptor) getSettingInt(key string, def int) int {
|
||||
v, ok, err := i.db.GetSetting(key)
|
||||
if err != nil || !ok {
|
||||
@@ -441,6 +460,12 @@ func (i *Interceptor) SetJudgeConfig(c JudgeConfig) error {
|
||||
if err := i.db.SetSetting(settingJudgeIncompleteScript, c.IncompleteScriptAction); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.ConfidenceThreshold <= 0 || c.ConfidenceThreshold > 1 {
|
||||
c.ConfidenceThreshold = defaultJudgeConfidence
|
||||
}
|
||||
if err := i.db.SetSetting(settingJudgeConfidence, strconv.FormatFloat(c.ConfidenceThreshold, 'f', 4, 64)); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package jev
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultBaseURL = "https://api.typesafe.ai"
|
||||
DefaultModel = "jev-latest"
|
||||
maxStateBytes = 24000
|
||||
)
|
||||
|
||||
// Config contains only the System One connection settings. Jev is deliberately
|
||||
// not represented as an agent/llm.Provider format.
|
||||
type Config struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Model string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
Model string `json:"model"`
|
||||
State any `json:"state"`
|
||||
Questions map[string]ChoiceQuestion `json:"questions"`
|
||||
}
|
||||
|
||||
type ChoiceQuestion struct {
|
||||
Type string `json:"type"`
|
||||
Instructions string `json:"instructions"`
|
||||
Criteria map[string]string `json:"criteria"`
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Answers map[string]Answer `json:"answers"`
|
||||
Usage map[string]any `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
type Answer struct {
|
||||
Type string `json:"type"`
|
||||
Choice string `json:"choice"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Probabilities map[string]float64 `json:"probabilities"`
|
||||
}
|
||||
|
||||
func (c Config) endpoint() (string, error) {
|
||||
base := strings.TrimSpace(c.BaseURL)
|
||||
if base == "" {
|
||||
base = DefaultBaseURL
|
||||
}
|
||||
base = strings.TrimRight(base, "/")
|
||||
if strings.HasSuffix(base, "/v1/systemone") {
|
||||
return base, nil
|
||||
}
|
||||
if strings.HasSuffix(base, "/v1") {
|
||||
return base + "/systemone", nil
|
||||
}
|
||||
u, err := url.Parse(base)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "", fmt.Errorf("System One Base URL 无效")
|
||||
}
|
||||
return base + "/v1/systemone", nil
|
||||
}
|
||||
|
||||
func BuildRequest(input intercept.ReviewInput, prompt, model string) (Request, error) {
|
||||
if strings.TrimSpace(model) == "" {
|
||||
model = DefaultModel
|
||||
}
|
||||
policy := strings.TrimSpace(prompt)
|
||||
if policy == "" {
|
||||
policy = "根据工具调用、参数、工作目录和脚本快照,选择 allow、ask 或 deny。"
|
||||
}
|
||||
if len(policy) > 6000 {
|
||||
policy = policy[:6000] + "…"
|
||||
}
|
||||
// System One accepts structured state. Keep policy and review evidence in one
|
||||
// bounded object; the model receives no requirement to emit free-form JSON.
|
||||
policy = "判定政策(仅作为选择依据;直接回答 choice,不要输出 JSON 或自由文本解释):\n" + policy
|
||||
state := map[string]any{"review_input": input, "policy": policy}
|
||||
b, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
if len(b) > maxStateBytes {
|
||||
// Arguments can be supplied by an untrusted tool. Preserve valid JSON while
|
||||
// bounding the request by replacing the evidence with a clipped JSON string.
|
||||
trimmed := string(b)
|
||||
if len(trimmed) > 16000 {
|
||||
trimmed = trimmed[:16000]
|
||||
}
|
||||
state = map[string]any{
|
||||
"review_input_json": trimmed,
|
||||
"policy": policy,
|
||||
"truncated": true,
|
||||
}
|
||||
}
|
||||
return Request{
|
||||
Model: model,
|
||||
State: state,
|
||||
Questions: map[string]ChoiceQuestion{
|
||||
"decision": {
|
||||
Type: "choice",
|
||||
Instructions: "Choose the action for this tool call. Apply the supplied policy and evidence.",
|
||||
Criteria: map[string]string{
|
||||
"allow": "Safe to execute without human review",
|
||||
"ask": "Needs human approval before executing",
|
||||
"deny": "Must be blocked",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c Config) Do(ctx context.Context, req Request) (Response, error) {
|
||||
endpoint, err := c.endpoint()
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
hc := c.Client
|
||||
if hc == nil {
|
||||
hc = http.DefaultClient
|
||||
}
|
||||
hreq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
hreq.Header.Set("Authorization", "Bearer "+strings.TrimSpace(c.APIKey))
|
||||
hreq.Header.Set("Content-Type", "application/json")
|
||||
resp, err := hc.Do(hreq)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return Response{}, fmt.Errorf("System One HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var out Response
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return Response{}, fmt.Errorf("System One 响应无效: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func DecisionFromResponse(resp Response, threshold float64, profileID int64) (intercept.Decision, error) {
|
||||
if threshold <= 0 || threshold > 1 {
|
||||
threshold = 0.55
|
||||
}
|
||||
a, ok := resp.Answers["decision"]
|
||||
if !ok {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("System One 缺少 decision 答案")
|
||||
}
|
||||
choice := strings.ToLower(strings.TrimSpace(a.Choice))
|
||||
if choice != "allow" && choice != "ask" && choice != "deny" {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("System One 返回了无效裁决 %q", a.Choice)
|
||||
}
|
||||
if a.Confidence < threshold {
|
||||
choice = "ask"
|
||||
}
|
||||
return intercept.Decision{
|
||||
Action: choice,
|
||||
ProfileID: profileID,
|
||||
Message: FormatMessage(choice, a.Confidence, a.Probabilities),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func FormatMessage(choice string, confidence float64, probabilities map[string]float64) string {
|
||||
parts := make([]string, 0, 3)
|
||||
for _, k := range []string{"allow", "ask", "deny"} {
|
||||
if p, ok := probabilities[k]; ok {
|
||||
parts = append(parts, fmt.Sprintf("%s %.0f%%", k, p*100))
|
||||
}
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return fmt.Sprintf("Jev / System One 判定:%s(置信度 %.0f%%)", choice, confidence*100)
|
||||
}
|
||||
return fmt.Sprintf("Jev / System One 判定:%s(置信度 %.0f%%;概率 %s)", choice, confidence*100, strings.Join(parts, ","))
|
||||
}
|
||||
|
||||
func (c Config) Review(ctx context.Context, input intercept.ReviewInput, prompt string, threshold float64, profileID int64) (intercept.Decision, error) {
|
||||
req, err := BuildRequest(input, prompt, c.Model)
|
||||
if err != nil {
|
||||
return intercept.Decision{ProfileID: profileID}, err
|
||||
}
|
||||
resp, err := c.Do(ctx, req)
|
||||
if err != nil {
|
||||
return intercept.Decision{ProfileID: profileID}, err
|
||||
}
|
||||
return DecisionFromResponse(resp, threshold, profileID)
|
||||
}
|
||||
|
||||
func (c Config) TestConnection(ctx context.Context) (time.Duration, string, error) {
|
||||
start := time.Now()
|
||||
req, err := BuildRequest(intercept.ReviewInput{Version: 5, Tool: "connection_test", Arguments: json.RawMessage(`{}`)}, "Reply with the safest choice for this harmless connection test.", c.Model)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
resp, err := c.Do(ctx, req)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
a, err := DecisionFromResponse(resp, 0, 0)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
return time.Since(start), a.Message, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package jev
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
)
|
||||
|
||||
func TestBuildRequestMapsReviewInputAndChoiceCriteria(t *testing.T) {
|
||||
req, err := BuildRequest(intercept.ReviewInput{Version: 5, Tool: "Bash", Arguments: json.RawMessage(`{"cmd":"ls"}`)}, "policy text", "jev-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.Model != "jev-test" || req.Questions["decision"].Type != "choice" {
|
||||
t.Fatalf("unexpected request: %#v", req)
|
||||
}
|
||||
b, _ := json.Marshal(req.State)
|
||||
if !strings.Contains(string(b), "Bash") || !strings.Contains(string(b), "policy text") {
|
||||
t.Fatalf("state did not include review and policy: %s", b)
|
||||
}
|
||||
if len(b) > maxStateBytes+2000 {
|
||||
t.Fatalf("state exceeded bound: %d", len(b))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequestBoundsLargeEvidence(t *testing.T) {
|
||||
args := json.RawMessage(`{"payload":"` + strings.Repeat("x", 50000) + `"}`)
|
||||
req, err := BuildRequest(intercept.ReviewInput{Version: 5, Tool: "Bash", Arguments: args}, strings.Repeat("policy ", 3000), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(req.State)
|
||||
if len(b) > maxStateBytes+500 {
|
||||
t.Fatalf("bounded state size=%d", len(b))
|
||||
}
|
||||
if !strings.Contains(string(b), `"truncated":true`) {
|
||||
t.Fatalf("large evidence was not marked truncated: %s", b[:min(len(b), 200)])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecisionFromResponseLowConfidenceForcesAsk(t *testing.T) {
|
||||
d, err := DecisionFromResponse(Response{Answers: map[string]Answer{
|
||||
"decision": {Choice: "allow", Confidence: 0.3, Probabilities: map[string]float64{"allow": 0.8, "ask": 0.1, "deny": 0.1}},
|
||||
}}, 0.55, 42)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Action != "ask" || d.ProfileID != 42 || !strings.Contains(d.Message, "置信度") {
|
||||
t.Fatalf("unexpected decision: %#v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecisionFromResponseRejectsMissingOrInvalidAnswer(t *testing.T) {
|
||||
for _, resp := range []Response{
|
||||
{Answers: map[string]Answer{}},
|
||||
{Answers: map[string]Answer{"decision": {Choice: "maybe", Confidence: 1}}},
|
||||
} {
|
||||
if _, err := DecisionFromResponse(resp, 0.55, 1); err == nil {
|
||||
t.Fatalf("expected invalid response error for %#v", resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemOneReviewAndConnectionTest(t *testing.T) {
|
||||
var gotAuth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/systemone" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
var req Request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Errorf("decode: %v", err)
|
||||
}
|
||||
if req.Questions["decision"].Criteria["deny"] == "" {
|
||||
t.Error("missing deny criterion")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"answers":{"decision":{"type":"choice","choice":"deny","confidence":0.91,"probabilities":{"allow":0.02,"ask":0.07,"deny":0.91}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
c := Config{BaseURL: srv.URL, APIKey: "secret", Model: "jev-latest", Client: srv.Client()}
|
||||
d, err := c.Review(context.Background(), intercept.ReviewInput{Version: 5, Tool: "Write", Arguments: json.RawMessage(`{}`)}, "policy", 0.55, 9)
|
||||
if err != nil || d.Action != "deny" {
|
||||
t.Fatalf("review decision=%#v err=%v", d, err)
|
||||
}
|
||||
if gotAuth != "Bearer secret" {
|
||||
t.Fatalf("auth=%q", gotAuth)
|
||||
}
|
||||
if _, _, err := c.TestConnection(context.Background()); err != nil {
|
||||
t.Fatalf("connection test: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,10 @@ func (s *Server) pgCreateConversation(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if req.LLMProfileID != nil {
|
||||
if p, err := pg.ProfileByID(*req.LLMProfileID); err == nil && p != nil && p.Format == "jev" {
|
||||
writeErr(w, 400, db.ErrJevProfileJudgeOnly.Error())
|
||||
return
|
||||
}
|
||||
if _, ok := s.loadProfileConfig(*req.LLMProfileID); !ok {
|
||||
writeErr(w, 400, "指定的 LLM 配置不存在或未设置 API Key")
|
||||
return
|
||||
@@ -136,6 +140,10 @@ func (s *Server) pgUpdateConversation(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if req.LLMProfileID != nil {
|
||||
if p, err := pg.ProfileByID(*req.LLMProfileID); err == nil && p != nil && p.Format == "jev" {
|
||||
writeErr(w, 400, db.ErrJevProfileJudgeOnly.Error())
|
||||
return
|
||||
}
|
||||
if _, ok := s.loadProfileConfig(*req.LLMProfileID); !ok {
|
||||
writeErr(w, 400, "指定的 LLM 配置不存在或未设置 API Key")
|
||||
return
|
||||
|
||||
+19
-17
@@ -325,15 +325,16 @@ type FindingDTO struct {
|
||||
ReportStale bool `json:"report_stale"`
|
||||
TrafficBindings []db.FindingTrafficBinding `json:"traffic_bindings,omitempty"`
|
||||
|
||||
ID string `json:"id"`
|
||||
FindingID string `json:"finding_id,omitempty"` // standalone findings-table id — the handle for status updates
|
||||
VulnClass string `json:"vulnclass"`
|
||||
Name string `json:"name,omitempty"` // 漏洞名称;为空时前端回退展示 vulnclass
|
||||
Severity string `json:"severity"` // critical | high | medium | low
|
||||
Status string `json:"status"` // pending | in_progress | confirmed | resolved | fixed | false_positive | ignored | duplicate | risk_accepted
|
||||
Summary string `json:"summary"`
|
||||
Evidence string `json:"evidence"`
|
||||
Report string `json:"report,omitempty"` // 详细报告(Markdown);仅详情接口返回,列表为空
|
||||
ID string `json:"id"`
|
||||
FindingID string `json:"finding_id,omitempty"` // standalone findings-table id — the handle for status updates
|
||||
VulnClass string `json:"vulnclass"`
|
||||
Name string `json:"name,omitempty"` // 漏洞名称;为空时前端回退展示 vulnclass
|
||||
Severity string `json:"severity"` // critical | high | medium | low
|
||||
Status string `json:"status"` // pending | in_progress | confirmed | resolved | fixed | false_positive | ignored | duplicate | risk_accepted
|
||||
Summary string `json:"summary"`
|
||||
Evidence string `json:"evidence"`
|
||||
Report string `json:"report,omitempty"` // 详细报告(Markdown);仅详情接口返回,列表为空
|
||||
ReportConversationID *int64 `json:"report_conversation_id,omitempty"`
|
||||
|
||||
IntentID string `json:"intent_id,omitempty"`
|
||||
ParamID string `json:"param_id,omitempty"`
|
||||
@@ -464,14 +465,15 @@ func findingFromDB(f *db.DBFinding, assets map[int64]*db.Asset) FindingDTO {
|
||||
FindingID: i64s(f.ID),
|
||||
TrafficCount: f.TrafficCount, EvidenceVersion: f.EvidenceVersion, ReportEvidenceVersion: f.ReportEvidenceVersion,
|
||||
ReportStale: f.Report != "" && f.EvidenceVersion != f.ReportEvidenceVersion, TrafficBindings: f.TrafficBindings,
|
||||
VulnClass: f.VulnClass,
|
||||
Name: f.Name,
|
||||
Severity: f.Severity,
|
||||
Status: status,
|
||||
Summary: f.Summary,
|
||||
Evidence: f.Evidence,
|
||||
Report: f.Report,
|
||||
TS: rfc3339(f.CreatedAt),
|
||||
VulnClass: f.VulnClass,
|
||||
Name: f.Name,
|
||||
Severity: f.Severity,
|
||||
Status: status,
|
||||
Summary: f.Summary,
|
||||
Evidence: f.Evidence,
|
||||
Report: f.Report,
|
||||
ReportConversationID: f.ReportConversationID,
|
||||
TS: rfc3339(f.CreatedAt),
|
||||
}
|
||||
if f.ExportCaseID > 0 {
|
||||
d.ID = "case:" + i64s(f.ExportCaseID)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/guard"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/intercept/jev"
|
||||
"github.com/Autumn-27/artex/llmrec"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
@@ -44,6 +45,17 @@ func (s *Server) wireInterceptReviewer() {
|
||||
if profileID == 0 {
|
||||
return intercept.Decision{}, fmt.Errorf("未配置可用的裁判模型")
|
||||
}
|
||||
profile, err := s.m.pg.ProfileByID(profileID)
|
||||
if err != nil || profile == nil {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("裁判模型 profile %d 不可用", profileID)
|
||||
}
|
||||
if profile.Format == "jev" {
|
||||
if strings.TrimSpace(profile.APIKey) == "" {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("Jev 判定模型未设置 API Key")
|
||||
}
|
||||
ctx = llmrec.WithWorker(ctx, judgeWorkerLane)
|
||||
return jev.Config{BaseURL: profile.BaseURL, APIKey: profile.APIKey, Model: profile.Model}.Review(ctx, input, prompt, s.m.interceptor.GetJudgeConfig().ConfidenceThreshold, profileID)
|
||||
}
|
||||
prov, _, ok := s.providerForProfile(profileID)
|
||||
if !ok {
|
||||
return intercept.Decision{ProfileID: profileID}, fmt.Errorf("裁判模型 profile %d 不可用", profileID)
|
||||
@@ -478,6 +490,9 @@ func (s *Server) interceptSetJudgeConfig(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if req.ConfidenceThreshold <= 0 || req.ConfidenceThreshold > 1 {
|
||||
req.ConfidenceThreshold = 0.55
|
||||
}
|
||||
if err := s.m.interceptor.SetJudgeConfig(req); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
|
||||
+51
-3
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"github.com/Autumn-27/artex/intercept/jev"
|
||||
"github.com/Autumn-27/artex/llmpool"
|
||||
"github.com/Autumn-27/artex/llmrec"
|
||||
"github.com/Autumn-27/artex/report"
|
||||
@@ -383,8 +384,9 @@ func (s *Server) loadLLMConfig() (agent.Config, bool) {
|
||||
|
||||
// saveLLMConfig persists the LLM config as the active "default" profile in PG.
|
||||
func (s *Server) saveLLMConfig(cfg agent.Config) error {
|
||||
// cfg.Provider() already returns one of the three valid format strings
|
||||
// (anthropic / openai / openai-responses), matching the DB CHECK constraint.
|
||||
// cfg.Provider() returns one of the chat format strings
|
||||
// (anthropic / openai / openai-responses), matching the DB CHECK constraint;
|
||||
// Jev is intentionally handled by the dedicated intercept path.
|
||||
format := cfg.Provider()
|
||||
var id int64
|
||||
// 这个 legacy 端点的请求体不含轮询/收发/输出上限参数,故把库里已存的值原样带回 —
|
||||
@@ -464,6 +466,9 @@ func maxTokensResolver(cfg agent.Config) func() int {
|
||||
// applyLLM (re)builds the planner/worker/main-agent from cfg and installs them on
|
||||
// the running engine as the GLOBAL active pair. Safe to call at runtime (UI configures LLM).
|
||||
func (s *Server) applyLLM(cfg agent.Config) error {
|
||||
if cfg.Jev {
|
||||
return fmt.Errorf("Jev System One 仅可用于拦截判定模型,不能作为聊天 provider")
|
||||
}
|
||||
var prov llm.Provider
|
||||
// A persisted active profile must use the same cached provider as task chains
|
||||
// and Agent bindings, otherwise each path owns a separate rate limiter.
|
||||
@@ -534,6 +539,9 @@ func (s *Server) loadProfileConfig(id int64) (agent.Config, bool) {
|
||||
if err != nil || p == nil {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
if p.Format == "jev" {
|
||||
return agent.Config{}, false
|
||||
}
|
||||
cfg := agent.ConfigFrom(p.Format, p.Model, p.BaseURL, p.APIKey, p.Proxy)
|
||||
cfg.RatePerSecond, cfg.RatePerMinute = p.RatePerSecond, p.RatePerMinute
|
||||
cfg.ContextWindowK = p.ContextWindowK
|
||||
@@ -599,6 +607,9 @@ func (s *Server) chatUnavailableReason() string {
|
||||
// ok=false when the profile is missing/invalid; pinned callers surface that error
|
||||
// while legacy callers retain their existing fallback behavior.
|
||||
func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool) {
|
||||
if p, err := s.m.pg.ProfileByID(id); err != nil || p == nil || p.Format == "jev" {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
s.provCacheMu.Lock()
|
||||
if e := s.provByProfile[id]; e != nil {
|
||||
s.provCacheMu.Unlock()
|
||||
@@ -1499,6 +1510,37 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Provider) == "jev" {
|
||||
apiKey := strings.TrimSpace(req.APIKey)
|
||||
baseURL, model := strings.TrimSpace(req.BaseURL), strings.TrimSpace(req.Model)
|
||||
if req.ProfileID != nil {
|
||||
if p, err := s.m.pg.ProfileByID(*req.ProfileID); err == nil && p != nil {
|
||||
if apiKey == "" {
|
||||
apiKey = p.APIKey
|
||||
}
|
||||
if baseURL == "" {
|
||||
baseURL = p.BaseURL
|
||||
}
|
||||
if model == "" {
|
||||
model = p.Model
|
||||
}
|
||||
}
|
||||
}
|
||||
if apiKey == "" {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "未提供 API Key"})
|
||||
return
|
||||
}
|
||||
if model == "" {
|
||||
model = jev.DefaultModel
|
||||
}
|
||||
lat, reply, err := (jev.Config{BaseURL: baseURL, APIKey: apiKey, Model: model}).TestConnection(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "latency_ms": lat.Milliseconds(), "model": model, "reply": truncateReply(reply)})
|
||||
return
|
||||
}
|
||||
cfg := agent.ConfigFrom(req.Provider, req.Model, req.BaseURL, req.APIKey, req.Proxy)
|
||||
// mirror production: send the SAME thinking params so a provider that rejects the
|
||||
// reasoning_effort/thinking field fails the test too (no false "test ok, run 400").
|
||||
@@ -1693,6 +1735,9 @@ func (s *Server) validateTaskProfileIDs(ids []int64) error {
|
||||
return fmt.Errorf("LLM 配置 id 无效或重复")
|
||||
}
|
||||
seen[id] = true
|
||||
if p, err := s.m.pg.ProfileByID(id); err == nil && p != nil && p.Format == "jev" {
|
||||
return db.ErrJevProfileJudgeOnly
|
||||
}
|
||||
if _, ok := s.loadProfileConfig(id); !ok {
|
||||
return fmt.Errorf("LLM 配置 #%d 不存在或未设置 API Key", id)
|
||||
}
|
||||
@@ -2332,7 +2377,10 @@ func (s *Server) findingsExport(w http.ResponseWriter, r *http.Request) {
|
||||
stamp := now.Format("20060102-150405")
|
||||
setDownload := func(contentType, filename string) {
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
// Keep an ASCII fallback for older clients and provide the real UTF-8
|
||||
// name through RFC 5987. Browsers otherwise commonly decode Chinese
|
||||
// names using the platform legacy code page.
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, sanitizeFilename(filename), url.PathEscape(filename)))
|
||||
}
|
||||
|
||||
switch format {
|
||||
|
||||
@@ -386,6 +386,10 @@ func (s *Server) pgSaveAgentConfig(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
if err := pg.SetAgentLLMProfile(a.Key, id); err != nil {
|
||||
if errors.Is(err, db.ErrJevProfileJudgeOnly) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -487,6 +491,9 @@ func (s *Server) pgGetAgent(w http.ResponseWriter, r *http.Request) {
|
||||
profs, _ := pg.ListProfiles()
|
||||
llmProfiles := make([]map[string]any, 0, len(profs))
|
||||
for _, p := range profs {
|
||||
if p.Format == "jev" {
|
||||
continue
|
||||
}
|
||||
llmProfiles = append(llmProfiles, map[string]any{
|
||||
"id": p.ID, "name": p.Name, "model": p.Model, "is_default": p.IsDefault,
|
||||
})
|
||||
@@ -1935,6 +1942,14 @@ func (s *Server) pgActivateProfile(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err := pg.SetActiveProfile(body.ID); err != nil {
|
||||
if errors.Is(err, db.ErrJevProfileJudgeOnly) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if errors.Is(err, db.ErrLLMProfileNotFound) {
|
||||
writeErr(w, 404, "LLM 配置不存在")
|
||||
return
|
||||
}
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -334,7 +334,7 @@ function LLMProfileRow({
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{profiles.map((p) => (
|
||||
{profiles.filter((p) => p.format !== "jev").map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
|
||||
@@ -207,6 +207,7 @@ const defaultJudge = (): JudgeConfig => ({
|
||||
ask_timeout_seconds: 300,
|
||||
ask_timeout_action: "deny",
|
||||
incomplete_script_action: "model",
|
||||
confidence_threshold: 0.55,
|
||||
});
|
||||
|
||||
function JudgeCard() {
|
||||
@@ -344,7 +345,7 @@ function JudgeCard() {
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">审批提示词</p>
|
||||
<p className="text-xs text-muted-foreground">模型据此判定 ALLOW / ASK / DENY,可直接编辑</p>
|
||||
<p className="text-xs text-muted-foreground">模型据此判定 ALLOW / ASK / DENY,可直接编辑;选 Jev 时会作为 System One 的 policy/instructions</p>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={restorePrompt} disabled={saving}>
|
||||
恢复默认模板
|
||||
@@ -373,12 +374,26 @@ function JudgeCard() {
|
||||
<SelectItem value={FOLLOW_ACTIVE}>跟随激活配置</SelectItem>
|
||||
{profiles.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}({p.model})
|
||||
{p.name}({p.model}){p.format === "jev" ? " · Jev / System One" : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Jev 低置信度阈值">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.01}
|
||||
value={cfg.confidence_threshold ?? 0.55}
|
||||
onChange={(e) => {
|
||||
const n = Number(e.target.value);
|
||||
if (Number.isFinite(n) && n >= 0 && n <= 1) patch({ confidence_threshold: n });
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">仅 Jev / System One 生效;置信度低于此值自动转人工,默认 0.55。</p>
|
||||
</Field>
|
||||
<Field label="每次模型判定超时(秒)">
|
||||
<Input
|
||||
type="number"
|
||||
|
||||
@@ -311,7 +311,7 @@ function ProfileSheet({
|
||||
}) {
|
||||
const isNew = !profile;
|
||||
const [name, setName] = React.useState("");
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses">("anthropic");
|
||||
const [format, setFormat] = React.useState<"anthropic" | "openai" | "openai-responses" | "jev">("anthropic");
|
||||
const [model, setModel] = React.useState("");
|
||||
const [baseUrl, setBaseUrl] = React.useState("");
|
||||
const [proxy, setProxy] = React.useState("");
|
||||
@@ -340,7 +340,7 @@ function ProfileSheet({
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
setName(profile?.name ?? "");
|
||||
setFormat(profile?.format === "openai" || profile?.format === "openai-responses" ? profile.format : "anthropic");
|
||||
setFormat(profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "jev" ? profile.format : "anthropic");
|
||||
setModel(profile?.model ?? "");
|
||||
setBaseUrl(profile?.base_url ?? "");
|
||||
setProxy(profile?.proxy ?? "");
|
||||
@@ -492,7 +492,7 @@ function ProfileSheet({
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>格式</Label>
|
||||
<Select value={format} onValueChange={(v) => setFormat(v as "anthropic" | "openai" | "openai-responses")}>
|
||||
<Select value={format} onValueChange={(v) => setFormat(v as "anthropic" | "openai" | "openai-responses" | "jev")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择格式" />
|
||||
</SelectTrigger>
|
||||
@@ -500,6 +500,7 @@ function ProfileSheet({
|
||||
<SelectItem value="anthropic">Anthropic</SelectItem>
|
||||
<SelectItem value="openai">OpenAI (Chat Completions)</SelectItem>
|
||||
<SelectItem value="openai-responses">OpenAI (Responses API)</SelectItem>
|
||||
<SelectItem value="jev">Jev / System One(仅拦截判定)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -916,7 +917,7 @@ export default function LLMPage() {
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="truncate font-medium text-sm">{p.name}</span>
|
||||
<Badge variant="outline" className="uppercase">
|
||||
{p.format}
|
||||
{p.format === "jev" ? "Jev / System One" : p.format}
|
||||
</Badge>
|
||||
<Badge variant="outline" className={cn("ml-auto", h.cls)} title={h.hint}>
|
||||
{h.label}
|
||||
@@ -946,13 +947,13 @@ export default function LLMPage() {
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
disabled={p.is_default}
|
||||
disabled={p.is_default || p.format === "jev"}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void activate(p.id, p.name);
|
||||
}}
|
||||
>
|
||||
{p.is_default ? "已激活" : "设为激活"}
|
||||
{p.is_default ? "已激活" : p.format === "jev" ? "判定专用" : "设为激活"}
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
|
||||
@@ -1324,7 +1324,7 @@ export default function SystemSettingsPage() {
|
||||
{!selected && pool.profile_id ? (
|
||||
<SelectItem value={pool.profile_id}>配置 #{pool.profile_id} 已删除/不可用</SelectItem>
|
||||
) : null}
|
||||
{llmProfiles.map((profile) => (
|
||||
{llmProfiles.filter((profile) => profile.format !== "jev").map((profile) => (
|
||||
<SelectItem key={profile.id} value={profile.id}>
|
||||
{profile.name} · {profile.model}
|
||||
</SelectItem>
|
||||
|
||||
@@ -51,6 +51,7 @@ export function FindingAutoChat({
|
||||
const [historyOpen, setHistoryOpen] = React.useState(false);
|
||||
const [history, setHistory] = React.useState<Conversation[]>([]);
|
||||
const cursor = React.useRef(0);
|
||||
const chatViewportRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const safeTitle = findingTitle.replace(/[\[\]\r\n]/g, " ").trim().slice(0, 100);
|
||||
const storageKey = `artex.finding.${agentKey}-conversation.${findingId}`;
|
||||
|
||||
@@ -136,6 +137,18 @@ export function FindingAutoChat({
|
||||
};
|
||||
}, [conversation, open, storageKey]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open || !conversation || loading || !messages.length) return;
|
||||
const viewport = chatViewportRef.current;
|
||||
if (!viewport) return;
|
||||
const key = `artex.conversation-scroll.${conversation.id}`;
|
||||
const saved = window.sessionStorage.getItem(key);
|
||||
requestAnimationFrame(() => {
|
||||
if (saved != null) viewport.scrollTop = Number(saved) || 0;
|
||||
else viewport.scrollTop = viewport.scrollHeight;
|
||||
});
|
||||
}, [conversation, loading, messages.length, open]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open || !conversation || !running) return;
|
||||
let live = true;
|
||||
@@ -271,7 +284,13 @@ export function FindingAutoChat({
|
||||
<XIcon />
|
||||
</Button>
|
||||
</header>
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto p-3">
|
||||
<div
|
||||
ref={chatViewportRef}
|
||||
onScroll={(event) => {
|
||||
if (conversation) window.sessionStorage.setItem(`artex.conversation-scroll.${conversation.id}`, String(event.currentTarget.scrollTop));
|
||||
}}
|
||||
className="min-h-0 min-w-0 flex-1 overflow-x-hidden overflow-y-auto p-3"
|
||||
>
|
||||
<div className="w-full min-w-0 max-w-full">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-10 text-muted-foreground text-sm">
|
||||
|
||||
@@ -18,6 +18,8 @@ function AuthenticatedImage({
|
||||
const [captureTimestamp, setCaptureTimestamp] = React.useState<string | null>(null);
|
||||
const [zoomed, setZoomed] = React.useState(false);
|
||||
const [zoomScale, setZoomScale] = React.useState(1);
|
||||
const [pan, setPan] = React.useState({ x: 0, y: 0 });
|
||||
const dragRef = React.useRef<{ x: number; y: number; panX: number; panY: number } | null>(null);
|
||||
const imageSrc = typeof src === "string" ? src : undefined;
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -29,6 +31,7 @@ function AuthenticatedImage({
|
||||
setCaptureTimestamp(null);
|
||||
setZoomed(false);
|
||||
setZoomScale(1);
|
||||
setPan({ x: 0, y: 0 });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
@@ -75,31 +78,55 @@ function AuthenticatedImage({
|
||||
onClick={() => renderedSrc && setZoomed(true)}
|
||||
aria-label="放大查看报告截图"
|
||||
>
|
||||
<img {...props} src={renderedSrc} alt={alt || "报告截图,点击放大"} />
|
||||
<img {...props} src={renderedSrc} alt={alt || "报告截图,点击放大"} draggable={false} onDragStart={(event) => event.preventDefault()} />
|
||||
{timestamp}
|
||||
</button>
|
||||
<Dialog
|
||||
open={zoomed}
|
||||
onOpenChange={(next) => {
|
||||
setZoomed(next);
|
||||
if (!next) setZoomScale(1);
|
||||
if (!next) {
|
||||
setZoomScale(1);
|
||||
setPan({ x: 0, y: 0 });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
showCloseButton
|
||||
className="flex max-h-[96dvh] max-w-[96vw] items-center justify-center overflow-hidden bg-black/85 p-3 backdrop-blur-sm sm:max-w-[96vw]"
|
||||
>
|
||||
<div className="relative flex max-h-[90dvh] max-w-full items-center justify-center overflow-auto">
|
||||
<div className="relative inline-block origin-center transition-transform duration-150" style={{ transform: `scale(${zoomScale})` }}>
|
||||
<div
|
||||
className="relative flex h-[90dvh] w-[90vw] max-w-full items-center justify-center overflow-hidden"
|
||||
onPointerDown={(event) => {
|
||||
if (zoomScale <= 1 || event.button !== 0) return;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
dragRef.current = { x: event.clientX, y: event.clientY, panX: pan.x, panY: pan.y };
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag) return;
|
||||
setPan({ x: drag.panX + event.clientX - drag.x, y: drag.panY + event.clientY - drag.y });
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
dragRef.current = null;
|
||||
event.currentTarget.releasePointerCapture?.(event.pointerId);
|
||||
}}
|
||||
onPointerCancel={() => { dragRef.current = null; }}
|
||||
style={{ cursor: zoomScale > 1 ? (dragRef.current ? "grabbing" : "grab") : "default" }}
|
||||
>
|
||||
<div className="relative inline-block origin-center" style={{ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoomScale})` }}>
|
||||
<img
|
||||
src={renderedSrc}
|
||||
alt={alt || "报告截图"}
|
||||
draggable={false}
|
||||
onDragStart={(event) => event.preventDefault()}
|
||||
className="max-h-[90dvh] max-w-[90vw] rounded-md object-contain"
|
||||
/>
|
||||
{timestamp}
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute top-3 left-3 z-10 flex items-center gap-1 rounded-lg bg-black/60 p-1 backdrop-blur-sm">
|
||||
<span className="px-2 text-xs font-medium text-white tabular-nums">{Math.round(zoomScale * 100)}%</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
|
||||
@@ -53,9 +53,10 @@ export function TaskLLMProfileChain({
|
||||
inputId,
|
||||
portalContainer,
|
||||
}: TaskLLMProfileChainProps) {
|
||||
const profilesByID = React.useMemo(() => new Map(profiles.map((profile) => [profile.id, profile])), [profiles]);
|
||||
const itemIDs = React.useMemo(() => profiles.map((profile) => profile.id), [profiles]);
|
||||
const profilesUnavailable = profiles.length === 0;
|
||||
const chatProfiles = React.useMemo(() => profiles.filter((profile) => profile.format !== "jev"), [profiles]);
|
||||
const profilesByID = React.useMemo(() => new Map(chatProfiles.map((profile) => [profile.id, profile])), [chatProfiles]);
|
||||
const itemIDs = React.useMemo(() => chatProfiles.map((profile) => profile.id), [chatProfiles]);
|
||||
const profilesUnavailable = chatProfiles.length === 0;
|
||||
const currentProfileID = activeProfileId && value.includes(activeProfileId) ? activeProfileId : value[0];
|
||||
const currentIndex = value.indexOf(currentProfileID);
|
||||
// api_key_hint is display-only and is empty for valid keys shorter than four
|
||||
|
||||
+22
-3
@@ -119,6 +119,24 @@ import type {
|
||||
SystemMetrics,
|
||||
} from "@/lib/types";
|
||||
|
||||
/**
|
||||
* Read a download name from Content-Disposition. RFC 5987's filename* is
|
||||
* preferred because it preserves UTF-8 names; older filename remains the
|
||||
* fallback for clients that do not understand it.
|
||||
*/
|
||||
export function downloadFilename(contentDisposition: string, fallback: string): string {
|
||||
const encoded = contentDisposition.match(/(?:^|;)\s*filename\*\s*=\s*UTF-8''([^;]+)/i)?.[1];
|
||||
if (encoded) {
|
||||
try {
|
||||
return decodeURIComponent(encoded.replace(/^"|"$/g, ""));
|
||||
} catch {
|
||||
// Fall through to the legacy token when a malformed header is received.
|
||||
}
|
||||
}
|
||||
const legacy = contentDisposition.match(/(?:^|;)\s*filename\s*=\s*(?:"([^"]*)"|([^;\s]+))/i);
|
||||
return (legacy?.[1] ?? legacy?.[2] ?? fallback).trim() || fallback;
|
||||
}
|
||||
|
||||
function getToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return localStorage.getItem("artex_token");
|
||||
@@ -534,6 +552,7 @@ export const api = {
|
||||
},
|
||||
workspaceDownload: async (path: string) => {
|
||||
let blob: Blob;
|
||||
let contentDisposition = "";
|
||||
if (MOCK) {
|
||||
blob = new Blob([`(demo)${path} 的下载内容示例。`], { type: "text/plain" });
|
||||
} else {
|
||||
@@ -542,12 +561,13 @@ export const api = {
|
||||
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
});
|
||||
if (!r.ok) throw new Error(`下载失败: ${r.status}`);
|
||||
contentDisposition = r.headers.get("Content-Disposition") ?? "";
|
||||
blob = await r.blob();
|
||||
}
|
||||
const objUrl = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = objUrl;
|
||||
a.download = path.split("/").pop() || "download";
|
||||
a.download = downloadFilename(contentDisposition, path.split("/").pop() || "download");
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
@@ -703,8 +723,7 @@ export const api = {
|
||||
const blob = await r.blob();
|
||||
// 文件名优先取后端 Content-Disposition,取不到则用默认名。
|
||||
const disp = r.headers.get("Content-Disposition") ?? "";
|
||||
const m = disp.match(/filename="?([^"]+)"?/);
|
||||
const filename = m?.[1] ?? `findings-export`;
|
||||
const filename = downloadFilename(disp, `findings-export`);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
|
||||
@@ -1109,7 +1109,7 @@ export interface NotificationDelivery {
|
||||
export interface LLMProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
format: "openai" | "anthropic" | "openai-responses";
|
||||
format: "openai" | "anthropic" | "openai-responses" | "jev";
|
||||
base_url?: string;
|
||||
proxy?: string;
|
||||
model: string;
|
||||
@@ -1433,6 +1433,7 @@ export interface JudgeConfig {
|
||||
ask_timeout_seconds: number; // 模型判 ask 转人工后的审批等待超时
|
||||
ask_timeout_action: "allow" | "deny"; // 审批超时后的默认动作
|
||||
incomplete_script_action: "ask" | "model"; // 脚本快照不完整时:人工审查或继续模型审查
|
||||
confidence_threshold: number; // Jev 置信度低于此值时转人工
|
||||
}
|
||||
|
||||
// JudgeUsage: 模型兜底审批(judge 通道)的累计 token 用量 + 近 N 天每日序列。
|
||||
|
||||
Reference in new issue
Block a user