feat(settings): use native image input and stack model settings
This commit is contained in:
parent
5129c3fe8a
commit
ca5057f8d9
|
|
@ -111,6 +111,7 @@ ai:
|
|||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||
api_key: sk-xxxxxxx
|
||||
model: qwen3-max
|
||||
# 图片输入默认按模型能力自动判断。自定义网关可在「测试图片」通过后启用,或设置 image_input: enabled。
|
||||
max_total_tokens: 120000
|
||||
max_completion_tokens: 32768
|
||||
# headers: 可选。追加或覆盖发给模型网关的 HTTP 请求头,值支持 ${ENV_VAR} 与 ${ENV_VAR:-默认值}。
|
||||
|
|
@ -144,7 +145,7 @@ ai:
|
|||
# model: qwen-plus
|
||||
# max_total_tokens: 120000
|
||||
# max_completion_tokens: 32768
|
||||
# 视觉分析(analyze_image MCP 工具;图片仅在单次 VL 调用中出现,Agent 上下文只保留文字摘要)
|
||||
# 可选的独立 analyze_image 工具配置。聊天图片可通过支持图片输入的模型通道发送。
|
||||
vision:
|
||||
enabled: false # true 且 model 非空时注册 analyze_image
|
||||
model: qwen-vl # VL 模型名(enabled 时必填)
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ type Model struct {
|
|||
Headers map[string]string `json:"headers,omitempty"`
|
||||
ContextWindow int `json:"contextWindow"`
|
||||
MaxTokens int `json:"maxTokens"`
|
||||
ImageInput *bool `json:"imageInput,omitempty"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
ExtraFields map[string]any `json:"extraFields,omitempty"`
|
||||
Compat map[string]any `json:"compat,omitempty"`
|
||||
|
|
@ -49,6 +50,11 @@ type NativeWorkflow struct {
|
|||
SkillPaths []string `json:"skillPaths,omitempty"`
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
MIMEType string `json:"mimeType"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
NativeWorkflow *NativeWorkflow `json:"nativeWorkflow,omitempty"`
|
||||
GenerateOnly bool `json:"generateOnly,omitempty"`
|
||||
|
|
@ -57,6 +63,7 @@ type Request struct {
|
|||
WorkingDir string `json:"workingDir,omitempty"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
Message string `json:"message"`
|
||||
Images []Image `json:"images,omitempty"`
|
||||
History json.RawMessage `json:"history,omitempty"`
|
||||
Model Model `json:"model"`
|
||||
FallbackModels []Model `json:"fallbackModels,omitempty"`
|
||||
|
|
|
|||
|
|
@ -724,6 +724,7 @@ type OpenAIConfig struct {
|
|||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
BaseURL string `yaml:"base_url" json:"base_url"`
|
||||
Model string `yaml:"model" json:"model"`
|
||||
ImageInput string `yaml:"image_input,omitempty" json:"image_input,omitempty"`
|
||||
MaxTotalTokens int `yaml:"max_total_tokens,omitempty" json:"max_total_tokens,omitempty"`
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens,omitempty" json:"max_completion_tokens,omitempty"`
|
||||
// Headers 追加或覆盖发给模型网关的 HTTP 请求头,值支持 ${ENV_VAR} 展开。
|
||||
|
|
@ -751,6 +752,7 @@ type AIChannelConfig struct {
|
|||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
BaseURL string `yaml:"base_url" json:"base_url"`
|
||||
Model string `yaml:"model" json:"model"`
|
||||
ImageInput string `yaml:"image_input,omitempty" json:"image_input,omitempty"`
|
||||
MaxTotalTokens int `yaml:"max_total_tokens,omitempty" json:"max_total_tokens,omitempty"`
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens,omitempty" json:"max_completion_tokens,omitempty"`
|
||||
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
|
||||
|
|
@ -769,6 +771,7 @@ func (c AIChannelConfig) ToOpenAIConfig() OpenAIConfig {
|
|||
APIKey: c.APIKey,
|
||||
BaseURL: c.BaseURL,
|
||||
Model: c.Model,
|
||||
ImageInput: c.ImageInput,
|
||||
MaxTotalTokens: c.MaxTotalTokens,
|
||||
MaxCompletionTokens: c.MaxCompletionTokens,
|
||||
Headers: ExpandHeaderMap(c.Headers),
|
||||
|
|
@ -788,6 +791,7 @@ func AIChannelFromOpenAI(id, name string, oa OpenAIConfig) AIChannelConfig {
|
|||
APIKey: oa.APIKey,
|
||||
BaseURL: oa.BaseURL,
|
||||
Model: oa.Model,
|
||||
ImageInput: oa.ImageInput,
|
||||
MaxTotalTokens: oa.MaxTotalTokens,
|
||||
MaxCompletionTokens: oa.MaxCompletionTokens,
|
||||
Headers: ExpandHeaderMap(oa.Headers),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ImageInputCapability resolves explicit channel settings and known official
|
||||
// models whose capabilities are newer than the bundled Pi model catalog.
|
||||
// A nil result lets Pi look up the model and endpoint in its catalog.
|
||||
func (c OpenAIConfig) ImageInputCapability() *bool {
|
||||
switch c.ImageInput {
|
||||
case "enabled":
|
||||
enabled := true
|
||||
return &enabled
|
||||
case "disabled":
|
||||
enabled := false
|
||||
return &enabled
|
||||
}
|
||||
endpoint, err := url.Parse(strings.TrimSpace(c.BaseURL))
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Host != "api.deepseek.com" || endpoint.User != nil {
|
||||
return nil
|
||||
}
|
||||
switch strings.TrimRight(endpoint.Path, "/") {
|
||||
case "", "/v1":
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
switch strings.TrimSpace(c.Model) {
|
||||
case "deepseek-flash", "deepseek-v4-flash-vision-exp":
|
||||
enabled := true
|
||||
return &enabled
|
||||
case "deepseek-v4-pro":
|
||||
enabled := false
|
||||
return &enabled
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestImageInputCapability(t *testing.T) {
|
||||
tests := []struct {
|
||||
url, model, mode string
|
||||
want string
|
||||
}{
|
||||
{"https://api.deepseek.com", "deepseek-flash", "", "enabled"},
|
||||
{"https://api.deepseek.com/v1", "deepseek-v4-pro", "", "disabled"},
|
||||
{"https://api.deepseek.com", "deepseek-flash", "disabled", "disabled"},
|
||||
{"https://custom.example/v1", "deepseek-flash", "", "unknown"},
|
||||
{"https://custom.example/v1", "local-model", "enabled", "enabled"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
capability := (OpenAIConfig{BaseURL: tt.url, Model: tt.model, ImageInput: tt.mode}).ImageInputCapability()
|
||||
got := "unknown"
|
||||
if capability != nil {
|
||||
got = "disabled"
|
||||
if *capability {
|
||||
got = "enabled"
|
||||
}
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("%s %s %s: got %s, want %s", tt.url, tt.model, tt.mode, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -38,7 +38,7 @@ func (h *AgentHandler) runMultiJSON(taskCtx, baseCtx context.Context, cancelWith
|
|||
var autoCancelledPendingExecutionIDs []string
|
||||
for {
|
||||
result, runErr = multiagent.RunMultiAgent(
|
||||
taskCtx,
|
||||
prep.withChatImages(taskCtx, curMsg),
|
||||
runCfg,
|
||||
&runCfg.MultiAgent,
|
||||
h.agent,
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ func (h *AgentHandler) runSingleJSON(taskCtx, baseCtx context.Context, cancelWit
|
|||
var autoCancelledPendingExecutionIDs []string
|
||||
for {
|
||||
result, runErr = multiagent.RunSingleAgent(
|
||||
taskCtx,
|
||||
prep.withChatImages(taskCtx, curMsg),
|
||||
runCfg,
|
||||
&runCfg.MultiAgent,
|
||||
h.agent,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,153 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
"cyberstrike-ai/internal/multiagent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
const (
|
||||
maxChatImageBytes = 8 << 20
|
||||
maxChatImageTotal = 12 << 20
|
||||
)
|
||||
|
||||
func (h *AgentHandler) authorizeChatAttachmentPaths(c *gin.Context, attachments []ChatAttachment) error {
|
||||
uploads := NewChatUploadsHandler(h.logger, h.db)
|
||||
root, err := filepath.Abs(chatUploadsDirName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, attachment := range attachments {
|
||||
if strings.TrimSpace(attachment.ServerPath) == "" {
|
||||
continue
|
||||
}
|
||||
path, err := validateChatAttachmentServerPath(attachment.ServerPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relative, err := filepath.Rel(root, path)
|
||||
if err != nil || !uploads.pathAllowed(c, relative) {
|
||||
return fmt.Errorf("无权访问附件 %s", attachment.FileName)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadChatImages(paths []string) ([]agentruntime.Image, error) {
|
||||
if len(paths) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rootPath, err := filepath.Abs(chatUploadsDirName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err := os.OpenRoot(rootPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
var images []agentruntime.Image
|
||||
total := 0
|
||||
for _, path := range paths {
|
||||
relative, err := filepath.Rel(rootPath, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
img, err := readChatImage(root, relative, maxChatImageTotal-total)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取附件 %s: %w", filepath.Base(path), err)
|
||||
}
|
||||
if img.Data != nil {
|
||||
images = append(images, img)
|
||||
total += len(img.Data)
|
||||
}
|
||||
}
|
||||
return images, nil
|
||||
}
|
||||
|
||||
func readChatImage(root *os.Root, name string, remaining int) (agentruntime.Image, error) {
|
||||
var fileImage agentruntime.Image
|
||||
if !filepath.IsLocal(name) {
|
||||
return fileImage, fmt.Errorf("附件路径无效")
|
||||
}
|
||||
for parent := filepath.Dir(name); parent != "."; parent = filepath.Dir(parent) {
|
||||
info, err := root.Lstat(parent)
|
||||
if err != nil {
|
||||
return fileImage, err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return fileImage, fmt.Errorf("附件目录无效")
|
||||
}
|
||||
}
|
||||
info, err := root.Lstat(name)
|
||||
if err != nil {
|
||||
return fileImage, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fileImage, fmt.Errorf("附件必须是普通文件")
|
||||
}
|
||||
f, err := root.Open(name)
|
||||
if err != nil {
|
||||
return fileImage, err
|
||||
}
|
||||
defer f.Close()
|
||||
opened, err := f.Stat()
|
||||
if err != nil {
|
||||
return fileImage, err
|
||||
}
|
||||
if !os.SameFile(info, opened) {
|
||||
return fileImage, fmt.Errorf("附件已变更,请重新上传")
|
||||
}
|
||||
var header [512]byte
|
||||
n, err := io.ReadFull(f, header[:])
|
||||
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
||||
return fileImage, err
|
||||
}
|
||||
mime := http.DetectContentType(header[:n])
|
||||
switch mime {
|
||||
case "image/png", "image/jpeg", "image/gif", "image/webp":
|
||||
default:
|
||||
return fileImage, nil
|
||||
}
|
||||
limit := min(maxChatImageBytes, remaining)
|
||||
if opened.Size() > int64(limit) || n > limit {
|
||||
return fileImage, fmt.Errorf("图片超过单张 8 MiB 或单次合计 12 MiB 的限制")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(io.MultiReader(bytes.NewReader(header[:n]), f), int64(limit)+1))
|
||||
if err != nil {
|
||||
return fileImage, err
|
||||
}
|
||||
if len(data) > limit {
|
||||
return fileImage, fmt.Errorf("图片超过单张 8 MiB 或单次合计 12 MiB 的限制")
|
||||
}
|
||||
dimensions, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || dimensions.Width <= 0 || dimensions.Height <= 0 {
|
||||
return fileImage, fmt.Errorf("图片格式无效")
|
||||
}
|
||||
if dimensions.Width > 8192 || dimensions.Height > 8192 || dimensions.Width*dimensions.Height > 32<<20 {
|
||||
return fileImage, fmt.Errorf("图片分辨率过大")
|
||||
}
|
||||
return agentruntime.Image{MIMEType: mime, Data: data}, nil
|
||||
}
|
||||
|
||||
func (p *multiAgentPrepared) withChatImages(ctx context.Context, message string) context.Context {
|
||||
if message == p.FinalMessage {
|
||||
return multiagent.WithChatImages(ctx, p.Images)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadChatImageChecksContentAndRejectsLinks(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file, err := os.Create(filepath.Join(dir, "upload.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := png.Encode(file, image.NewRGBA(image.Rect(0, 0, 24, 24))); err != nil {
|
||||
file.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "notes.png"), []byte("plain text"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
img, err := readChatImage(root, "upload.txt", maxChatImageTotal)
|
||||
if err != nil || img.MIMEType != "image/png" || len(img.Data) == 0 {
|
||||
t.Fatalf("image mime/bytes/error = %q/%d/%v", img.MIMEType, len(img.Data), err)
|
||||
}
|
||||
ignored, err := readChatImage(root, "notes.png", maxChatImageTotal)
|
||||
if err != nil || len(ignored.Data) != 0 {
|
||||
t.Fatalf("plain text treated as image: %v, %d bytes", err, len(ignored.Data))
|
||||
}
|
||||
if _, err := readChatImage(root, "upload.txt", 1); err == nil {
|
||||
t.Fatal("image exceeded the remaining size budget")
|
||||
}
|
||||
if err := os.Symlink("upload.txt", filepath.Join(dir, "link.png")); err != nil {
|
||||
t.Skipf("symlinks unavailable: %v", err)
|
||||
}
|
||||
if _, err := readChatImage(root, "link.png", maxChatImageTotal); err == nil {
|
||||
t.Fatal("symlink was accepted as an image attachment")
|
||||
}
|
||||
}
|
||||
|
|
@ -282,7 +282,8 @@ type GetConfigResponse struct {
|
|||
MultiAgent config.MultiAgentPublic `json:"multi_agent,omitempty"`
|
||||
C2 config.C2Public `json:"c2"`
|
||||
|
||||
ContextWindowDefaults map[string]int `json:"context_window_defaults,omitempty"`
|
||||
ContextWindowDefaults map[string]int `json:"context_window_defaults,omitempty"`
|
||||
ImageInputDefaults map[string]bool `json:"image_input_defaults,omitempty"`
|
||||
}
|
||||
|
||||
// ToolConfigInfo 工具配置信息
|
||||
|
|
@ -378,15 +379,26 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
|||
}
|
||||
|
||||
windowDefaults := make(map[string]int)
|
||||
imageDefaults := make(map[string]bool)
|
||||
for id, channel := range h.config.AI.Channels {
|
||||
if window := channel.ToOpenAIConfig().DefaultContextWindow(); window > 0 {
|
||||
model := channel.ToOpenAIConfig()
|
||||
if window := model.DefaultContextWindow(); window > 0 {
|
||||
windowDefaults[id] = window
|
||||
}
|
||||
model.ImageInput = ""
|
||||
if capability := model.ImageInputCapability(); capability != nil {
|
||||
imageDefaults[id] = *capability
|
||||
}
|
||||
}
|
||||
if len(h.config.AI.Channels) == 0 {
|
||||
if window := h.config.OpenAI.DefaultContextWindow(); window > 0 {
|
||||
windowDefaults[""] = window
|
||||
}
|
||||
model := h.config.OpenAI
|
||||
model.ImageInput = ""
|
||||
if capability := model.ImageInputCapability(); capability != nil {
|
||||
imageDefaults[""] = *capability
|
||||
}
|
||||
}
|
||||
|
||||
response, err := maskedConfigResponse(GetConfigResponse{
|
||||
|
|
@ -409,6 +421,7 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
|||
MultiAgent: multiPub,
|
||||
|
||||
ContextWindowDefaults: windowDefaults,
|
||||
ImageInputDefaults: imageDefaults,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "配置序列化失败"})
|
||||
|
|
@ -1337,6 +1350,7 @@ type TestOpenAIRequest struct {
|
|||
MaxTotalTokens int `json:"max_total_tokens,omitempty"`
|
||||
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
|
||||
ContextProfile string `json:"context_profile,omitempty"`
|
||||
TestImage bool `json:"test_image,omitempty"`
|
||||
}
|
||||
|
||||
// DetectContextRequest probes model metadata without issuing a completion.
|
||||
|
|
@ -1492,6 +1506,10 @@ func (h *ConfigHandler) testOpenAI(c *gin.Context, req TestOpenAIRequest) {
|
|||
c.JSON(http.StatusBadRequest, gin.H{"error": "模型不能为空"})
|
||||
return
|
||||
}
|
||||
if req.TestImage {
|
||||
h.testChannelImage(c, req, resolvedHeaders)
|
||||
return
|
||||
}
|
||||
|
||||
baseURL := strings.TrimSuffix(strings.TrimSpace(req.BaseURL), "/")
|
||||
if baseURL == "" {
|
||||
|
|
@ -2346,6 +2364,11 @@ func updateOpenAIConfig(doc *yaml.Node, cfg config.OpenAIConfig) {
|
|||
setStringInMap(openaiNode, "api_key", cfg.APIKey)
|
||||
setStringInMap(openaiNode, "base_url", cfg.BaseURL)
|
||||
setStringInMap(openaiNode, "model", cfg.Model)
|
||||
if cfg.ImageInput != "" {
|
||||
setStringInMap(openaiNode, "image_input", cfg.ImageInput)
|
||||
} else {
|
||||
removeKeyFromMap(openaiNode, "image_input")
|
||||
}
|
||||
setStringMapInMap(openaiNode, "headers", cfg.Headers)
|
||||
if cfg.MaxTotalTokens > 0 {
|
||||
setIntInMap(openaiNode, "max_total_tokens", cfg.MaxTotalTokens)
|
||||
|
|
@ -2413,6 +2436,9 @@ func updateAIConfig(doc *yaml.Node, cfg config.AIConfig) error {
|
|||
setStringInMap(channelNode, "api_key", ch.APIKey)
|
||||
setStringInMap(channelNode, "base_url", ch.BaseURL)
|
||||
setStringInMap(channelNode, "model", ch.Model)
|
||||
if ch.ImageInput != "" {
|
||||
setStringInMap(channelNode, "image_input", ch.ImageInput)
|
||||
}
|
||||
setStringMapInMap(channelNode, "headers", ch.Headers)
|
||||
if ch.MaxTotalTokens > 0 {
|
||||
setIntInMap(channelNode, "max_total_tokens", ch.MaxTotalTokens)
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ type AIChannelUpdate struct {
|
|||
BaseURL *string `json:"base_url,omitempty"`
|
||||
APIKey *string `json:"api_key,omitempty"`
|
||||
Model *string `json:"model,omitempty"`
|
||||
ImageInput *string `json:"image_input,omitempty"`
|
||||
ContextProfile *string `json:"context_profile,omitempty"`
|
||||
ContextWindow *int `json:"context_window,omitempty"`
|
||||
MaxTotalTokens *int `json:"max_total_tokens,omitempty"`
|
||||
|
|
@ -36,6 +37,20 @@ func (u AIChannelUpdate) merge(cfg *config.Config) (*config.AIConfig, error) {
|
|||
if !ok || id == "" {
|
||||
return nil, fmt.Errorf("通道已不存在,请刷新配置后重试")
|
||||
}
|
||||
if u.ImageInput != nil {
|
||||
switch strings.TrimSpace(*u.ImageInput) {
|
||||
case "", "auto":
|
||||
ch.ImageInput = ""
|
||||
case "enabled", "disabled":
|
||||
ch.ImageInput = strings.TrimSpace(*u.ImageInput)
|
||||
default:
|
||||
return nil, fmt.Errorf("图片输入模式无效")
|
||||
}
|
||||
} else if (u.Model != nil && strings.TrimSpace(*u.Model) != ch.Model) ||
|
||||
(u.BaseURL != nil && strings.TrimSpace(*u.BaseURL) != ch.BaseURL) ||
|
||||
(u.Provider != nil && strings.TrimSpace(*u.Provider) != ch.Provider) {
|
||||
ch.ImageInput = ""
|
||||
}
|
||||
|
||||
for _, field := range []struct{ target, value *string }{
|
||||
{&ch.Name, u.Name},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
"cyberstrike-ai/internal/multiagent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/image/draw"
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/basicfont"
|
||||
"golang.org/x/image/math/fixed"
|
||||
)
|
||||
|
||||
var imageProbeCode = regexp.MustCompile(`\b[2-9]{6}\b`)
|
||||
|
||||
func (h *ConfigHandler) testChannelImage(c *gin.Context, req TestOpenAIRequest, headers map[string]string) {
|
||||
h.mu.RLock()
|
||||
model, _, _ := h.config.ResolveAIChannel(req.ChannelID)
|
||||
runtime := h.config.AgentRuntime
|
||||
h.mu.RUnlock()
|
||||
model.Provider, model.BaseURL, model.Model = req.Provider, req.BaseURL, strings.TrimSpace(req.Model)
|
||||
model.APIKey, model.Headers, model.ContextProfile = req.APIKey, headers, req.ContextProfile
|
||||
|
||||
var digits [6]byte
|
||||
_, _ = rand.Read(digits[:])
|
||||
for i := range digits {
|
||||
digits[i] = '2' + digits[i]%8
|
||||
}
|
||||
code := string(digits[:])
|
||||
small := image.NewRGBA(image.Rect(0, 0, 58, 24))
|
||||
draw.Draw(small, small.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||
label := font.Drawer{Dst: small, Src: image.NewUniform(color.Black), Face: basicfont.Face7x13, Dot: fixed.P(8, 17)}
|
||||
label.DrawString(code)
|
||||
large := image.NewRGBA(image.Rect(0, 0, 464, 192))
|
||||
draw.NearestNeighbor.Scale(large, large.Bounds(), small, small.Bounds(), draw.Src, nil)
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, large); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成测试图片失败"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 35*time.Second)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
result, err := multiagent.ProbeImageInput(ctx, runtime, model, agentruntime.Image{MIMEType: "image/png", Data: encoded.Bytes()})
|
||||
response := gin.H{"success": false, "model": model.Model, "latency_ms": time.Since(started).Milliseconds()}
|
||||
switch {
|
||||
case err != nil || result == nil || result.Status != "completed":
|
||||
response["error"] = "图片请求失败,请确认当前通道的模型和 API 协议支持图片输入"
|
||||
case !matchesImageProbeCode(result.Response, code):
|
||||
response["error"] = "模型未正确读取测试图片中的字符"
|
||||
default:
|
||||
response["success"] = true
|
||||
}
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
func matchesImageProbeCode(response, expected string) bool {
|
||||
codes := imageProbeCode.FindAllString(response, 2)
|
||||
return len(codes) == 1 && codes[0] == expected
|
||||
}
|
||||
|
|
@ -261,7 +261,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) {
|
|||
})
|
||||
|
||||
result, runErr = multiagent.RunMultiAgent(
|
||||
taskCtxLoop,
|
||||
prep.withChatImages(taskCtxLoop, curFinalMessage),
|
||||
runCfg,
|
||||
&runCfg.MultiAgent,
|
||||
h.agent,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"cyberstrike-ai/internal/agent"
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
"cyberstrike-ai/internal/audit"
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
|
|
@ -21,6 +22,7 @@ type multiAgentPrepared struct {
|
|||
CreatedNew bool
|
||||
History []agent.ChatMessage
|
||||
FinalMessage string
|
||||
Images []agentruntime.Image
|
||||
RoleTools []string
|
||||
AssistantMessageID string
|
||||
UserMessageID string
|
||||
|
|
@ -209,12 +211,19 @@ func (h *AgentHandler) prepareMultiAgentSession(req *ChatRequest, c *gin.Context
|
|||
|
||||
var savedPaths []string
|
||||
if len(req.Attachments) > 0 {
|
||||
if err := h.authorizeChatAttachmentPaths(c, req.Attachments); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var aerr error
|
||||
savedPaths, aerr = saveAttachmentsToDateAndConversationDir(req.Attachments, conversationID, h.logger)
|
||||
if aerr != nil {
|
||||
return nil, fmt.Errorf("保存上传文件失败: %w", aerr)
|
||||
}
|
||||
}
|
||||
images, err := loadChatImages(savedPaths)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finalMessage = appendAttachmentsToMessage(finalMessage, req.Attachments, savedPaths)
|
||||
|
||||
userContent := userMessageContentForStorage(req.Message, req.Attachments, savedPaths)
|
||||
|
|
@ -246,6 +255,7 @@ func (h *AgentHandler) prepareMultiAgentSession(req *ChatRequest, c *gin.Context
|
|||
CreatedNew: createdNew,
|
||||
History: agentHistoryMessages,
|
||||
FinalMessage: finalMessage,
|
||||
Images: images,
|
||||
RoleTools: roleTools,
|
||||
AssistantMessageID: assistantMessageID,
|
||||
UserMessageID: userMessageID,
|
||||
|
|
|
|||
|
|
@ -5025,7 +5025,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
|
|||
"post": map[string]interface{}{
|
||||
"tags": []string{"配置管理"},
|
||||
"summary": "测试OpenAI API连接",
|
||||
"description": "测试指定的OpenAI/Claude API配置是否可用,发送一个最小请求验证连通性。",
|
||||
"description": "测试指定的 OpenAI/Claude API 配置。启用 test_image 时通过 Pi 发送合成图片并验证识别结果。",
|
||||
"operationId": "testOpenAI",
|
||||
"requestBody": map[string]interface{}{
|
||||
"required": true,
|
||||
|
|
@ -5035,10 +5035,11 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
|
|||
"type": "object",
|
||||
"required": []string{"api_key", "model"},
|
||||
"properties": map[string]interface{}{
|
||||
"provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai/claude)", "example": "openai"},
|
||||
"base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认根据provider自动选择)"},
|
||||
"api_key": map[string]interface{}{"type": "string", "description": "API密钥"},
|
||||
"model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "gpt-4"},
|
||||
"provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai/claude)", "example": "openai"},
|
||||
"base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认根据provider自动选择)"},
|
||||
"api_key": map[string]interface{}{"type": "string", "description": "API密钥"},
|
||||
"model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "gpt-4"},
|
||||
"test_image": map[string]interface{}{"type": "boolean", "description": "验证模型是否能读取合成图片"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -248,7 +248,7 @@ func (h *AgentHandler) SingleAgentLoopStream(c *gin.Context) {
|
|||
})
|
||||
|
||||
result, runErr = multiagent.RunSingleAgent(
|
||||
taskCtxLoop,
|
||||
prep.withChatImages(taskCtxLoop, curFinalMessage),
|
||||
runCfg,
|
||||
&runCfg.MultiAgent,
|
||||
h.agent,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package multiagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
"cyberstrike-ai/internal/config"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ProbeImageInput sends a synthetic image through the channel's Pi adapter.
|
||||
func ProbeImageInput(ctx context.Context, runtime config.AgentRuntimeConfig, oa config.OpenAIConfig, img agentruntime.Image) (*agentruntime.Result, error) {
|
||||
oa.ImageInput = "enabled"
|
||||
oa.Reasoning.Mode = "off"
|
||||
oa.MaxCompletionTokens = 128
|
||||
model := piModelConfig(oa, nil, "image-test")
|
||||
req := agentruntime.Request{
|
||||
RunID: uuid.NewString(), GenerateOnly: true, Model: model,
|
||||
Message: "Read the six digits printed in the supplied image. Reply with only those digits. If there is no image, reply NO_IMAGE.",
|
||||
Images: []agentruntime.Image{img}, Tools: []agentruntime.Tool{}, MaxTurns: 1,
|
||||
}
|
||||
return (agentruntime.Pi{NodePath: runtime.NodePath, WorkerPath: runtime.WorkerPath}).Run(ctx, req, nil, nil, nil)
|
||||
}
|
||||
|
|
@ -66,5 +66,5 @@ func piModelConfig(oa config.OpenAIConfig, intent *reasoning.ClientIntent, conve
|
|||
compat["requiresReasoningContentOnAssistantMessages"] = true
|
||||
compat["maxTokensField"] = "max_tokens"
|
||||
}
|
||||
return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: extra, Compat: compat, CompactToolJSON: oa.IsEconomyContextProfile()}
|
||||
return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), ImageInput: oa.ImageInputCapability(), Thinking: thinking, ExtraFields: extra, Compat: compat, CompactToolJSON: oa.IsEconomyContextProfile()}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,15 @@ type piRun struct {
|
|||
extraExecute agentruntime.ToolExecutor
|
||||
}
|
||||
|
||||
type chatImagesKey struct{}
|
||||
|
||||
func WithChatImages(ctx context.Context, images []agentruntime.Image) context.Context {
|
||||
if len(images) == 0 {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, chatImagesKey{}, images)
|
||||
}
|
||||
|
||||
func runPiSingle(ctx context.Context, cfg *config.Config, ag *agent.Agent, db *database.DB, logger *zap.Logger,
|
||||
conversationID, projectID, message string, history []agent.ChatMessage, roleTools []string,
|
||||
progress func(string, string, interface{}), intent *reasoning.ClientIntent, extra string) (*RunResult, error) {
|
||||
|
|
@ -300,6 +309,9 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) {
|
|||
req := agentruntime.Request{RunID: runID, ConversationID: r.conversationID, SystemPrompt: r.systemPrompt, Message: message, History: history,
|
||||
Model: piModelConfig(oa, r.reasoning, r.conversationID),
|
||||
Tools: tools, SessionDir: filepath.Join(root, agentruntime.ConversationStorageKey(r.conversationID), key), MaxTurns: max}
|
||||
if !r.child {
|
||||
req.Images, _ = ctx.Value(chatImagesKey{}).([]agentruntime.Image)
|
||||
}
|
||||
if strings.TrimSpace(r.conversationID) == "" {
|
||||
req.SessionDir = ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { InMemoryCredentialStore, type Model, type Api, type AssistantMessage, type Message } from "@earendil-works/pi-ai";
|
||||
import { InMemoryCredentialStore, type Model, type Api, type AssistantMessage, type ImageContent, type Message } from "@earendil-works/pi-ai";
|
||||
import {
|
||||
createAgentSession, createExtensionRuntime, ModelRuntime, SessionManager, SettingsManager,
|
||||
type AgentSession, type ResourceLoader, type ToolDefinition,
|
||||
|
|
@ -17,6 +17,7 @@ interface ModelConfig {
|
|||
provider: string; api?: "openai-completions" | "openai-responses" | "anthropic-messages";
|
||||
id: string; baseUrl: string; apiKey: string; headers?: Record<string, string>;
|
||||
contextWindow: number; maxTokens: number; thinking?: string;
|
||||
imageInput?: boolean;
|
||||
extraFields?: Record<string, unknown>;
|
||||
compat?: Record<string, unknown>; inputBudget?: number;
|
||||
compactToolJSON?: boolean;
|
||||
|
|
@ -26,6 +27,7 @@ interface RunRequest {
|
|||
nativeWorkflow?: { receipts?: NativeReceipt[]; resumeRequired?: boolean; context?: string; completionTool: string; checkpointTool?: string; segmentSeconds?: number; skillPaths?: string[] };
|
||||
generateOnly?: boolean;
|
||||
runId: string; conversationId: string; systemPrompt: string; message: string;
|
||||
images?: Omit<ImageContent, "type">[];
|
||||
workingDir?: string;
|
||||
model: ModelConfig; tools: { name: string; description: string; parameters: Record<string, unknown>; outputSchema?: Record<string, unknown>; annotations?: Record<string, boolean>; exposure?: ToolDefinition["exposure"]; namespace?: string; promptSnippet?: string; promptGuidelines?: string[]; executionMode?: "parallel" | "sequential" }[];
|
||||
sessionDir?: string; history?: Record<string, any>[]; maxTurns: number;
|
||||
|
|
@ -201,15 +203,22 @@ async function run(req: RunRequest): Promise<void> {
|
|||
const runtime = await ModelRuntime.create({ credentials: new InMemoryCredentialStore(), modelsPath: null,
|
||||
modelsStorePath: join(scratch, "models.json"), allowModelNetwork: false, refreshOnCreate: false });
|
||||
const configs = [req.model, ...(req.fallbackModels ?? [])];
|
||||
const catalog = runtime.getModels();
|
||||
const physical: Model<Api>[] = [];
|
||||
const modelConfigs = new Map<string, ModelConfig>();
|
||||
for (const [index, config] of configs.entries()) {
|
||||
const provider = index === 0 ? "cyberstrike" : "cyberstrike-" + index;
|
||||
const api = config.api ?? (config.provider === "claude" ? "anthropic-messages" : "openai-completions");
|
||||
const endpoint = config.baseUrl.replace(/\/+$/, "");
|
||||
const matchingModels = catalog.filter(model => model.id === config.id && model.baseUrl.replace(/\/+$/, "") === endpoint);
|
||||
// OpenAI's catalog can prefer Responses for a model also used through Chat Completions.
|
||||
const catalogModel = matchingModels.find(model => model.api === api) ??
|
||||
matchingModels.find(model => api === "openai-completions" && model.api === "openai-responses");
|
||||
const imageInput = config.imageInput ?? catalogModel?.input.includes("image") ?? false;
|
||||
runtime.registerProvider(provider, {
|
||||
api, baseUrl: config.baseUrl, headers: config.headers,
|
||||
models: [{ id: config.id, name: config.id, api, reasoning: config.thinking !== "off" && !!config.thinking,
|
||||
input: ["text", "image"], contextWindow: config.contextWindow || 128000, maxTokens: config.maxTokens || 16384, compat: config.compat,
|
||||
input: imageInput ? ["text", "image"] : ["text"], contextWindow: config.contextWindow || 128000, maxTokens: config.maxTokens || 16384, compat: config.compat,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
||||
});
|
||||
await runtime.setRuntimeApiKey(provider, config.apiKey || "local-no-key");
|
||||
|
|
@ -259,9 +268,14 @@ async function run(req: RunRequest): Promise<void> {
|
|||
model = runtime.getModel("cyberstrike-router", "auto")!;
|
||||
}
|
||||
if (!model) throw new Error("Model registration failed");
|
||||
const images: ImageContent[] = physical.some(model => model.input.includes("image"))
|
||||
? (req.images ?? []).map(image => ({ ...image, type: "image" })) : [];
|
||||
if (req.generateOnly) {
|
||||
const input = SessionManager.inMemory(scratch);
|
||||
importHistory(input, req.history ?? [], req.model);
|
||||
if (images.length) {
|
||||
input.appendMessage({ role: "user", content: [{ type: "text", text: req.message }, ...images], timestamp: Date.now() });
|
||||
}
|
||||
const answer = await runtime.completeSimple(physical[0], {
|
||||
systemPrompt: req.systemPrompt,
|
||||
messages: input.buildSessionContext().messages as Message[],
|
||||
|
|
@ -360,13 +374,16 @@ async function run(req: RunRequest): Promise<void> {
|
|||
data = { assistantMessageEvent: delta };
|
||||
}
|
||||
if (e.type === "agent_end") data = {};
|
||||
if (e.message?.role === "user" && Array.isArray(e.message.content)) {
|
||||
data = { ...e, message: { ...e.message, content: e.message.content.filter((block: { type: string }) => block.type !== "image") } };
|
||||
}
|
||||
void send({ type: "event", event: { type: e.type, data } }).catch(() => session?.abort());
|
||||
});
|
||||
// Pi accepts steering before prompt() and drains it during the run.
|
||||
for (const note of steeringBeforeSession ?? []) await session.steer(note);
|
||||
steeringBeforeSession = undefined;
|
||||
if (canceled) throw new Error("Run canceled before start");
|
||||
await session.prompt(req.message, { expandPromptTemplates: false });
|
||||
await session.prompt(req.message, { expandPromptTemplates: false, images: images.length ? images : undefined });
|
||||
if (canceled || lastAssistant?.stopReason === "aborted") status = "canceled";
|
||||
else if (lastAssistant?.stopReason === "error") { status = "failed"; failure = lastAssistant.errorMessage || "Model request failed"; }
|
||||
else if (status === "completed" && lastAssistant?.stopReason === "length") status = "output_truncated";
|
||||
|
|
|
|||
|
|
@ -79,6 +79,30 @@ function userTexts(body) {
|
|||
typeof m.content === "string" ? m.content : m.content.map(block => block.text).join(""));
|
||||
}
|
||||
|
||||
test("native chat images reach image-capable models without appearing in host events", { timeout: 30000 }, async t => {
|
||||
const fixture = await startFixture(t, (_body, res) => {
|
||||
sse(res, { role: "assistant", content: "done" }, "stop");
|
||||
});
|
||||
const image = {
|
||||
mimeType: "image/png",
|
||||
data: "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKElEQVR4nO3NsQ0AAAzCMP5/un0CNkuZ41wybXsHAAAAAAAAAAAAxR4yw/wuPL6QkAAAAABJRU5ErkJggg==",
|
||||
};
|
||||
for (const capability of [true, false, undefined]) {
|
||||
const req = request(fixture.url);
|
||||
req.tools = [];
|
||||
req.images = [image];
|
||||
req.model.imageInput = capability;
|
||||
const { result, records } = await invoke(t, req);
|
||||
assert.equal(result.status, "completed", result.error);
|
||||
const user = fixture.requests.at(-1).messages.find(m => m.role === "user");
|
||||
const content = Array.isArray(user.content) ? user.content : [{ type: "text", text: user.content }];
|
||||
assert.ok(content.some(block => block.type === "text" && block.text.includes(req.message)),
|
||||
JSON.stringify(content.filter(block => block.type === "text")));
|
||||
assert.equal(content.filter(block => block.type === "image_url").length, capability ? 1 : 0);
|
||||
assert.ok(!JSON.stringify(records).includes(image.data));
|
||||
}
|
||||
});
|
||||
|
||||
test("real Pi SDK streams, invokes only host tools and restores persisted sessions", { timeout: 30000 }, async t => {
|
||||
const fixture = await startFixture(t, (body, res, count) => {
|
||||
if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "call-1", type: "function", function: { name: "echo", arguments: '{"text":"hello"}' } }] }, "tool_calls");
|
||||
|
|
|
|||
|
|
@ -74,12 +74,8 @@
|
|||
overflow: auto;
|
||||
padding: 2px;
|
||||
}
|
||||
.settings-probe-secondary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||
gap: 16px;
|
||||
.settings-audit-model {
|
||||
margin-top: 18px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--semi-color-border);
|
||||
}
|
||||
.settings-probe-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||
|
|
@ -127,7 +123,6 @@
|
|||
@media (max-width: 480px) {
|
||||
.settings-channel-panel .semi-card-header-wrapper { flex-direction: column-reverse; align-items: stretch; }
|
||||
.settings-channel-panel .semi-card-header-wrapper-title { margin-inline: 0; }
|
||||
.settings-probe-secondary { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
|
||||
.settings-update-source-form {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
* 编辑所选模型通道,并使用表单中的值测试连接或探测模型能力。
|
||||
*/
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { Banner, Button, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
|
||||
import { Banner, Button, Collapse, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
|
||||
import { api } from '../../../lib/http';
|
||||
import { useT } from '../../../lib/i18n';
|
||||
import { modelChannelOptions, selectedModelChannelName } from '../../../lib/model-channel';
|
||||
|
|
@ -57,6 +57,7 @@ function channelValues(channel) {
|
|||
base_url: channel.base_url || '',
|
||||
api_key: channel.api_key || '',
|
||||
model: channel.model || '',
|
||||
image_input: channel.image_input || '',
|
||||
context_profile: channel.context_profile || '',
|
||||
context_window: channel.context_window > 0 ? String(channel.context_window) : '',
|
||||
max_total_tokens: channel.max_total_tokens || 0,
|
||||
|
|
@ -131,13 +132,15 @@ function ProbeOutput({ state, defaultWindow }) {
|
|||
);
|
||||
}
|
||||
|
||||
if (key === 'audit' || key === 'vision') {
|
||||
if (key === 'audit' || key === 'image') {
|
||||
return (
|
||||
<div className="settings-probe-result">
|
||||
{payload.success ? (
|
||||
<KeyValueList
|
||||
columns={3}
|
||||
items={summarizeTest(t, payload)}
|
||||
items={summarizeTest(t, payload).map((item, index) => key === 'image' && index === 0
|
||||
? { ...item, value: <Tag color="green">{t('settingsProbe.imageReadSuccess', null, '图片读取成功')}</Tag> }
|
||||
: item)}
|
||||
/>
|
||||
) : (
|
||||
<Banner type="danger" bordered closeIcon={null} description={payload.error || t('settingsBasic.testFailed', null, '连接失败')} />
|
||||
|
|
@ -193,6 +196,10 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
const [drafts, setDrafts] = useState({});
|
||||
const draft = drafts[channelId] || {};
|
||||
const form = { ...baseline, ...draft };
|
||||
const sameModelEndpoint = ['model', 'base_url', 'provider'].every(field => form[field] === baseline[field]);
|
||||
const imageMode = draft.image_input ?? (sameModelEndpoint ? baseline.image_input : '');
|
||||
const imageDefault = sameModelEndpoint ? config.image_input_defaults?.[legacy ? '' : channelId] : undefined;
|
||||
const imageEnabled = imageMode === 'enabled' || (imageMode !== 'disabled' && imageDefault === true);
|
||||
const defaultWindow = config.context_window_defaults?.[legacy ? '' : channelId];
|
||||
const useDefaultWindow = defaultWindow > 0 && !form.context_window && !Object.hasOwn(draft, 'context_window')
|
||||
&& ['base_url', 'model', 'context_profile'].every(field => form[field] === baseline[field]);
|
||||
|
|
@ -202,7 +209,7 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState(null);
|
||||
const [applyPending, setApplyPending] = useState(false);
|
||||
const locked = !canWrite || saving;
|
||||
const locked = !canWrite || saving || busy === 'image';
|
||||
const channelOptions = legacy
|
||||
? [{ value: MAIN_CHANNEL, label: t('settingsProbe.mainChannel', null, '主模型通道') }]
|
||||
: modelChannelOptions(Object.entries(channels));
|
||||
|
|
@ -219,9 +226,13 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
});
|
||||
};
|
||||
const update = (key, value) => {
|
||||
setState(EMPTY_PROBE);
|
||||
setDrafts(current => {
|
||||
const next = { ...current[channelId] };
|
||||
if (value === String(baseline[key])) delete next[key];
|
||||
const modelFields = ['model', 'base_url', 'provider'];
|
||||
if (modelFields.includes(key) && value !== form[key]) delete next.image_input;
|
||||
const baselineValue = key === 'image_input' && !sameModelEndpoint ? '' : baseline[key];
|
||||
if (value === String(baselineValue)) delete next[key];
|
||||
else next[key] = value;
|
||||
return { ...current, [channelId]: next };
|
||||
});
|
||||
|
|
@ -333,28 +344,6 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
context_profile: form.context_profile
|
||||
});
|
||||
|
||||
// 视觉模型:vision 段优先,空字段回退 openai 段;密钥为 ******** 时由服务端恢复。
|
||||
const vision = config.vision || {};
|
||||
const [visionState, setVisionState] = useState({ key: '', payload: null, error: null });
|
||||
const [visionBusy, setVisionBusy] = useState(false);
|
||||
const testVision = async () => {
|
||||
if (!canWrite) return;
|
||||
setVisionBusy(true);
|
||||
setVisionState({ key: 'vision', payload: null, error: null });
|
||||
try {
|
||||
const payload = await api.post('/config/test-vision', {
|
||||
channel_id: channelId === MAIN_CHANNEL ? undefined : channelId,
|
||||
vision,
|
||||
openai: config.openai || {}
|
||||
});
|
||||
setVisionState({ key: 'vision', payload, error: null });
|
||||
} catch (error) {
|
||||
setVisionState({ key: 'vision', payload: null, error });
|
||||
} finally {
|
||||
setVisionBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// The server selects the configured audit backend and resolves inherited fields.
|
||||
const auditModel = config.hitl?.audit_model || {};
|
||||
const auditBackend = (config.hitl?.audit_backend || '').trim().toLowerCase();
|
||||
|
|
@ -364,6 +353,9 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
const auditProtocol = auditTypeSafe ? 'TypeSafe / Jev'
|
||||
: auditClaude ? 'Claude (Anthropic Messages)'
|
||||
: t('settingsProbe.compatible', null, '兼容 OpenAI 的接口');
|
||||
const auditSource = auditTypeSafe || ['provider', 'base_url', 'api_key', 'model'].some(key => auditModel[key])
|
||||
? auditModel.model || auditProtocol
|
||||
: t('settingsProbe.auditInherit', null, '继承主模型');
|
||||
const auditURLPlaceholder = auditTypeSafe ? 'https://api.typesafe.ai'
|
||||
: config.openai?.base_url || (auditClaude ? 'https://api.anthropic.com' : 'https://api.openai.com/v1');
|
||||
const [auditDraft, setAuditDraft] = useState({});
|
||||
|
|
@ -444,7 +436,12 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
<Input value={form.base_url} onChange={value => update('base_url', value)} readOnly={locked} placeholder="https://api.openai.com/v1" />
|
||||
</label>
|
||||
<label className="settings-field">
|
||||
<Text type="tertiary" size="small">{t('settingsBasic.model', null, '模型')}</Text>
|
||||
<Space spacing={6}>
|
||||
<Text type="tertiary" size="small">{t('settingsBasic.model', null, '模型')}</Text>
|
||||
{(imageEnabled || state.key === 'image' && state.payload?.success) && (
|
||||
<Tag size="small" color="green">{t('settingsProbe.imageInputSupported', null, '支持图片')}</Tag>
|
||||
)}
|
||||
</Space>
|
||||
<Input value={form.model} onChange={value => update('model', value)} readOnly={locked} placeholder="gpt-4o-mini" />
|
||||
</label>
|
||||
<label className="settings-field">
|
||||
|
|
@ -513,6 +510,18 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
>
|
||||
{t('settingsBasic.test', null, '测试连接')}
|
||||
</Button>
|
||||
<Button
|
||||
loading={busy === 'image'}
|
||||
disabled={locked || !!busy}
|
||||
onClick={() => run('image', '/config/test-openai', { ...probeBody(), test_image: true })}
|
||||
>
|
||||
{t('settingsProbe.testImage', null, '测试图片')}
|
||||
</Button>
|
||||
{!imageEnabled && state.key === 'image' && state.payload?.success && (
|
||||
<Button type="tertiary" disabled={locked || !!busy} onClick={() => update('image_input', 'enabled')}>
|
||||
{t('settingsProbe.enableImageInput', null, '为此通道启用图片')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
loading={busy === 'context'}
|
||||
disabled={locked || !!busy}
|
||||
|
|
@ -536,57 +545,51 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
|
|||
</Space>
|
||||
<ProbeOutput state={state} defaultWindow={useDefaultWindow ? defaultWindow : 0} />
|
||||
|
||||
<div className="settings-probe-secondary">
|
||||
<div className="settings-probe-card">
|
||||
<Text strong>{t('settings.visionTestTitle', null, '视觉模型连接测试')}</Text>
|
||||
<Hint>
|
||||
{t('settingsProbe.visionHint', { model: vision.model || '—' }, `当前视觉模型 ${vision.model || '—'},未填写密钥时使用主模型配置。`)}
|
||||
</Hint>
|
||||
<Space>
|
||||
<Button size="small" loading={visionBusy} disabled={!canWrite} onClick={testVision}>
|
||||
{t('settingsBasic.testVision', null, '测试视觉模型')}
|
||||
</Button>
|
||||
<Collapse className="settings-audit-model">
|
||||
<Collapse.Panel itemKey="audit-model" header={(
|
||||
<Space wrap spacing={8}>
|
||||
<Text strong>{t('settingsProbe.auditModelTitle', null, '审计模型')}</Text>
|
||||
<Text type="tertiary" size="small">{auditSource}</Text>
|
||||
</Space>
|
||||
<ProbeOutput state={visionState} />
|
||||
</div>
|
||||
<div className="settings-probe-card">
|
||||
<Text strong>{t('settingsProbe.auditTitle', null, '审计模型连接测试')}</Text>
|
||||
<Tag>{auditProtocol}</Tag>
|
||||
<Hint>
|
||||
{auditTypeSafe
|
||||
? t('settingsProbe.auditTypeSafeHint', null, '按已配置的 TypeSafe / Jev 后端测试。地址和模型留空使用 Jev 默认值;密钥沿用已保存的审计密钥,不继承主模型。')
|
||||
: t('settingsProbe.auditChatHint', null, '按已配置的审计模型协议测试。地址和模型留空继承主模型;密钥留空或显示 ******** 时沿用已保存的审计密钥,未配置则继承主模型。')}
|
||||
</Hint>
|
||||
<div className="settings-probe-inline">
|
||||
{[
|
||||
['base_url', 'baseUrl', 'API 地址', auditURLPlaceholder],
|
||||
['api_key', 'apiKey', 'API 密钥', '********'],
|
||||
['model', 'model', '模型', auditTypeSafe ? 'jev-latest' : config.openai?.model || '']
|
||||
].map(([field, key, fallback, placeholder]) => (
|
||||
<label key={field} className="settings-field">
|
||||
<Text type="tertiary" size="small">{t('settingsBasic.' + key, null, fallback)}</Text>
|
||||
<Input
|
||||
value={auditForm[field]}
|
||||
onChange={value => {
|
||||
setAuditDraft(current => ({ ...current, [field]: value }));
|
||||
setAuditState(EMPTY_PROBE);
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
readOnly={!canWrite || auditBusy}
|
||||
mode={field === 'api_key' ? 'password' : undefined}
|
||||
autoComplete={field === 'api_key' ? 'new-password' : undefined}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
)}>
|
||||
<div className="settings-probe-card">
|
||||
<div><Tag size="small">{auditProtocol}</Tag></div>
|
||||
<Hint>
|
||||
{auditTypeSafe
|
||||
? t('settingsProbe.auditTypeSafeHint', null, '按已配置的 TypeSafe / Jev 后端测试。地址和模型留空使用 Jev 默认值;密钥沿用已保存的审计密钥,不继承主模型。')
|
||||
: t('settingsProbe.auditChatHint', null, '按已配置的审计模型协议测试。地址和模型留空继承主模型;密钥留空或显示 ******** 时沿用已保存的审计密钥,未配置则继承主模型。')}
|
||||
</Hint>
|
||||
<div className="settings-probe-inline">
|
||||
{[
|
||||
['base_url', 'baseUrl', 'API 地址', auditURLPlaceholder],
|
||||
['api_key', 'apiKey', 'API 密钥', '********'],
|
||||
['model', 'model', '模型', auditTypeSafe ? 'jev-latest' : config.openai?.model || '']
|
||||
].map(([field, key, fallback, placeholder]) => (
|
||||
<label key={field} className="settings-field">
|
||||
<Text type="tertiary" size="small">{t('settingsBasic.' + key, null, fallback)}</Text>
|
||||
<Input
|
||||
value={auditForm[field]}
|
||||
onChange={value => {
|
||||
setAuditDraft(current => ({ ...current, [field]: value }));
|
||||
setAuditState(EMPTY_PROBE);
|
||||
}}
|
||||
placeholder={placeholder}
|
||||
readOnly={!canWrite || auditBusy}
|
||||
mode={field === 'api_key' ? 'password' : undefined}
|
||||
autoComplete={field === 'api_key' ? 'new-password' : undefined}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Space>
|
||||
<Button size="small" loading={auditBusy} disabled={!canWrite} onClick={testAuditModel}>
|
||||
{t('settingsProbe.testAuditModel', null, '测试审计模型')}
|
||||
</Button>
|
||||
</Space>
|
||||
<ProbeOutput state={auditState} />
|
||||
</div>
|
||||
<Space>
|
||||
<Button size="small" loading={auditBusy} disabled={!canWrite} onClick={testAuditModel}>
|
||||
{t('settingsProbe.testAuditModel', null, '测试审计模型')}
|
||||
</Button>
|
||||
</Space>
|
||||
<ProbeOutput state={auditState} />
|
||||
</div>
|
||||
</div>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
</SectionCard>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
import { test, expect, visit, label, UI_PERMISSIONS } from './fixtures.mjs';
|
||||
|
||||
test.use({ appPermissions: [...UI_PERMISSIONS, 'config:write'] });
|
||||
|
||||
test('model channel tests native image input while audit settings start collapsed', async ({ page, mockApi }) => {
|
||||
mockApi.respond('GET', '/api/config', { json: {
|
||||
ai: { default_channel: 'deepseek', channels: {
|
||||
deepseek: { name: 'DeepSeek', model: 'deepseek-flash', base_url: 'https://api.deepseek.com', api_key: '********' }
|
||||
} },
|
||||
image_input_defaults: { deepseek: true },
|
||||
hitl: { audit_model: {} },
|
||||
tools: []
|
||||
} });
|
||||
mockApi.respond('POST', '/api/config/test-openai', { json: {
|
||||
success: true, model: 'deepseek-flash', latency_ms: 120
|
||||
} });
|
||||
const main = await visit(page, 'settings?section=models');
|
||||
const testImage = main.getByRole('button', { name: label('settingsProbe.testImage'), exact: true });
|
||||
const testAudit = main.getByRole('button', { name: label('settingsProbe.testAuditModel'), exact: true });
|
||||
await expect(main.getByText(label('settingsProbe.imageInputSupported'), { exact: true })).toBeVisible();
|
||||
await expect(testAudit).toBeHidden();
|
||||
await testImage.click();
|
||||
await expect(main.getByText(label('settingsProbe.imageReadSuccess'), { exact: true })).toBeVisible();
|
||||
const imageCalls = mockApi.calls('POST', '/api/config/test-openai');
|
||||
expect(imageCalls).toHaveLength(1);
|
||||
expect(imageCalls[0].body).toMatchObject({ channel_id: 'deepseek', model: 'deepseek-flash', test_image: true });
|
||||
await main.getByText(label('settingsProbe.auditModelTitle'), { exact: true }).click();
|
||||
await expect(testAudit).toBeVisible();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(testAudit).toBeVisible();
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391);
|
||||
});
|
||||
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-Du_eCXFg.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(a,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(c,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(c,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(i,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(r,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(o,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-DZWb6CUM.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(a,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(c,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(c,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(i,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(r,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(o,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-BxhBcqdj.js";import{E as i,P as a,k as o}from"./index-Du_eCXFg.js";import"./c2-shared-BvpuXQ_S.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-BxhBcqdj.js";import{E as i,P as a,k as o}from"./index-DZWb6CUM.js";import"./c2-shared-CZQii_1n.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
|
|
@ -1 +1 @@
|
|||
import{I as e,L as t}from"./index-Du_eCXFg.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
import{I as e,L as t}from"./index-DZWb6CUM.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,F as i,H as a,L as o,M as s,W as c,ot as l,st as u}from"./semi-BxhBcqdj.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-Du_eCXFg.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(o,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(s,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(r,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(a,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,onChange:O,style:{width:260}}),(0,E.jsx)(a,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,F as i,H as a,L as o,M as s,W as c,ot as l,st as u}from"./semi-BxhBcqdj.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-DZWb6CUM.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(o,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(s,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(r,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(a,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,onChange:O,style:{width:260}}),(0,E.jsx)(a,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-BxhBcqdj.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-Du_eCXFg.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-BxhBcqdj.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-DZWb6CUM.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-Du_eCXFg.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(s,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(c,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(c,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(i,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(r,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(o,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-BxhBcqdj.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-DZWb6CUM.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(s,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(c,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(c,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(i,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(r,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(o,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-probe-secondary{border-top:1px solid var(--semi-color-border);grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;margin-top:18px;padding-top:16px;display:grid}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}.settings-probe-secondary{grid-template-columns:minmax(0,1fr)}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}
|
||||
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-tags{flex-wrap:wrap;gap:6px;max-height:190px;padding:2px;display:flex;overflow:auto}.settings-audit-model{border-top:1px solid var(--semi-color-border);margin-top:18px}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{At as t,F as n,L as r,W as i,st as a}from"./semi-BxhBcqdj.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-Du_eCXFg.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(r,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(r,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(t,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{At as t,F as n,L as r,W as i,st as a}from"./semi-BxhBcqdj.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-DZWb6CUM.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(r,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(r,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(t,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -18,7 +18,7 @@
|
|||
} catch (error) { /* first paint fallback */ }
|
||||
})();
|
||||
</script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-Du_eCXFg.js"></script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-DZWb6CUM.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-BxhBcqdj.js">
|
||||
|
|
|
|||
|
|
@ -4712,6 +4712,12 @@
|
|||
"branchCreated": "تم إنشاء فرع إعادة الاختبار. تابع التحقّق في ذلك الفرع."
|
||||
},
|
||||
"settingsProbe": {
|
||||
"auditModelTitle": "نموذج التدقيق",
|
||||
"auditInherit": "يرث النموذج الأساسي",
|
||||
"imageInputSupported": "يدعم الصور",
|
||||
"testImage": "اختبار صورة",
|
||||
"imageReadSuccess": "تمت قراءة الصورة بنجاح",
|
||||
"enableImageInput": "تفعيل الصور لهذه القناة",
|
||||
"auditTitle": "اختبار اتصال نموذج التدقيق",
|
||||
"auditTypeSafeHint": "يختبر خلفية TypeSafe / Jev المضبوطة. يستخدم العنوان والنموذج الفارغان قيم Jev الافتراضية. يستخدم المفتاح الفارغ أو المخفي مفتاح التدقيق المحفوظ ولا يرث مفتاح النموذج الرئيسي.",
|
||||
"auditChatHint": "يختبر بروتوكول نموذج التدقيق المضبوط. يرث العنوان والنموذج الفارغان إعدادات النموذج الرئيسي. يستخدم المفتاح الفارغ أو المخفي مفتاح التدقيق المحفوظ، أو مفتاح النموذج الرئيسي إذا لم يُضبط مفتاح للتدقيق."
|
||||
|
|
|
|||
|
|
@ -3159,6 +3159,12 @@
|
|||
"cleanupDuration": "Cleanup duration"
|
||||
},
|
||||
"settingsProbe": {
|
||||
"auditModelTitle": "Audit model",
|
||||
"auditInherit": "Inherits primary model",
|
||||
"imageInputSupported": "Image input",
|
||||
"testImage": "Test image",
|
||||
"imageReadSuccess": "Image read successfully",
|
||||
"enableImageInput": "Enable images for this channel",
|
||||
"auditTitle": "Audit model connection test",
|
||||
"auditTypeSafeHint": "Tests the configured TypeSafe / Jev backend. Blank URL and model use Jev defaults. A blank or masked key uses the saved audit key; the main model key is never inherited.",
|
||||
"auditChatHint": "Tests the configured audit model protocol. Blank URL and model inherit the main model. A blank or masked key uses the saved audit key, or inherits the main model key if none is configured.",
|
||||
|
|
|
|||
|
|
@ -5748,6 +5748,12 @@
|
|||
"reviewEvidence": "Намерение проверки и результаты"
|
||||
},
|
||||
"settingsProbe": {
|
||||
"auditModelTitle": "Модель аудита",
|
||||
"auditInherit": "Наследует основную модель",
|
||||
"imageInputSupported": "Поддержка изображений",
|
||||
"testImage": "Проверить изображение",
|
||||
"imageReadSuccess": "Изображение распознано",
|
||||
"enableImageInput": "Включить изображения для этого канала",
|
||||
"auditTitle": "Проверка подключения модели аудита",
|
||||
"auditTypeSafeHint": "Проверяет настроенный TypeSafe / Jev. Пустые URL и модель используют значения Jev по умолчанию. Пустой или скрытый ключ берётся из настроек аудита; ключ основной модели не наследуется.",
|
||||
"auditChatHint": "Проверяет протокол настроенной модели аудита. Пустые URL и модель наследуются от основной модели. Пустой или скрытый ключ использует сохранённый ключ аудита, а при его отсутствии — ключ основной модели."
|
||||
|
|
|
|||
|
|
@ -3147,6 +3147,12 @@
|
|||
"cleanupDuration": "清理耗时"
|
||||
},
|
||||
"settingsProbe": {
|
||||
"auditModelTitle": "审计模型",
|
||||
"auditInherit": "继承主模型",
|
||||
"imageInputSupported": "支持图片",
|
||||
"testImage": "测试图片",
|
||||
"imageReadSuccess": "图片读取成功",
|
||||
"enableImageInput": "为此通道启用图片",
|
||||
"auditTitle": "审计模型连接测试",
|
||||
"auditTypeSafeHint": "按已配置的 TypeSafe / Jev 后端测试。地址和模型留空使用 Jev 默认值;密钥沿用已保存的审计密钥,不继承主模型。",
|
||||
"auditChatHint": "按已配置的审计模型协议测试。地址和模型留空继承主模型;密钥留空或显示 ******** 时沿用已保存的审计密钥,未配置则继承主模型。",
|
||||
|
|
|
|||
Loading…
Reference in New Issue