fix(settings,chat): add audit model save controls and compact HITL reviewer spacing

This commit is contained in:
Sycun 2026-11-25 19:20:20 +08:00
parent 550331e8e3
commit 0a7020f62a
51 changed files with 659 additions and 109 deletions

View File

@ -767,10 +767,11 @@ type UpdateConfigRequest struct {
Quake *config.SpaceSearchConfig `json:"quake,omitempty"`
Shodan *config.SpaceSearchConfig `json:"shodan,omitempty"`
MCP *config.MCPConfig `json:"mcp,omitempty"`
Tools []ToolEnableStatus `json:"tools,omitempty"`
Agent *AgentConfigUpdate `json:"agent,omitempty"`
Hitl *config.HitlConfig `json:"hitl,omitempty"`
Knowledge *config.KnowledgeConfig `json:"knowledge,omitempty"`
Tools []ToolEnableStatus `json:"tools,omitempty"`
Agent *AgentConfigUpdate `json:"agent,omitempty"`
Hitl *config.HitlConfig `json:"hitl,omitempty"`
HitlAuditModel *HitlAuditModelUpdate `json:"hitl_audit_model,omitempty"`
Knowledge *config.KnowledgeConfig `json:"knowledge,omitempty"`
Robots *config.RobotsConfig `json:"robots,omitempty"`
MultiAgent *config.MultiAgentAPIUpdate `json:"multi_agent,omitempty"`
C2 *config.C2APIUpdate `json:"c2,omitempty"`
@ -851,10 +852,27 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
}
req.AI, req.AIChannel = ai, nil
}
auditModelUpdate := req.HitlAuditModel != nil
if auditModelUpdate {
if req.Hitl != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "hitl_audit_model 不能与 hitl 同时更新"})
return
}
hitl, err := req.HitlAuditModel.merge(h.config)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
req.Hitl, req.HitlAuditModel = hitl, nil
}
if err := restoreConfigRequestSecrets(&req, h.config); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if auditModelUpdate && req.Hitl.EffectiveAuditBackend() == config.HitlAuditBackendTypeSafe && strings.TrimSpace(req.Hitl.AuditModel.APIKey) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "TypeSafe API Key 不能为空"})
return
}
if req.OpenAI != nil {
if err := config.ValidateContextSettings("openai", req.OpenAI.ContextWindow, req.OpenAI.ContextProfile); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
@ -873,6 +891,7 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
previousProxy := h.config.Proxy
previousRuntime := h.config.AgentRuntime
previousAI, previousOpenAI := h.config.AI, h.config.OpenAI
previousHitl := cloneHitlConfig(h.config.Hitl)
saved := false
defer func() {
if !saved {
@ -881,6 +900,9 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
if channelUpdate {
h.config.AI, h.config.OpenAI = previousAI, previousOpenAI
}
if auditModelUpdate {
h.config.Hitl = previousHitl
}
}
}()
if req.Proxy != nil {

View File

@ -0,0 +1,90 @@
package handler
import (
"fmt"
"maps"
"net/url"
"slices"
"strings"
"cyberstrike-ai/internal/config"
)
// HitlAuditModelUpdate edits hitl.audit_backend and hitl.audit_model without
// overwriting unrelated HITL settings such as tool_whitelist or prompts.
type HitlAuditModelUpdate struct {
AuditBackend *string `json:"audit_backend,omitempty"`
Provider *string `json:"provider,omitempty"`
BaseURL *string `json:"base_url,omitempty"`
APIKey *string `json:"api_key,omitempty"`
Model *string `json:"model,omitempty"`
}
func cloneHitlConfig(src config.HitlConfig) config.HitlConfig {
dst := src
dst.ToolWhitelist = slices.Clone(src.ToolWhitelist)
dst.AuditModel.Headers = maps.Clone(src.AuditModel.Headers)
if src.AuditModel.Reasoning.ExtraRequestFields != nil {
dst.AuditModel.Reasoning.ExtraRequestFields = maps.Clone(src.AuditModel.Reasoning.ExtraRequestFields)
}
if src.DefaultTimeoutSeconds != nil {
v := *src.DefaultTimeoutSeconds
dst.DefaultTimeoutSeconds = &v
}
if src.RetentionDays != nil {
v := *src.RetentionDays
dst.RetentionDays = &v
}
return dst
}
func (u HitlAuditModelUpdate) merge(cfg *config.Config) (*config.HitlConfig, error) {
hitl := cloneHitlConfig(cfg.Hitl)
if u.AuditBackend != nil {
raw := strings.ToLower(strings.TrimSpace(*u.AuditBackend))
switch raw {
case "", config.HitlAuditBackendOpenAI:
hitl.AuditBackend = config.HitlAuditBackendOpenAI
case config.HitlAuditBackendTypeSafe, "jev", "type-safe", "typesafe-ai":
hitl.AuditBackend = config.HitlAuditBackendTypeSafe
default:
return nil, fmt.Errorf("不支持的审计后端: %s", strings.TrimSpace(*u.AuditBackend))
}
}
if u.Provider != nil {
raw := strings.ToLower(strings.TrimSpace(*u.Provider))
switch raw {
case "":
hitl.AuditModel.Provider = ""
case "openai", "openai_compatible":
hitl.AuditModel.Provider = "openai_compatible"
case "claude", "anthropic":
hitl.AuditModel.Provider = "claude"
default:
return nil, fmt.Errorf("不支持的审计模型提供商: %s", strings.TrimSpace(*u.Provider))
}
}
if u.BaseURL != nil {
raw := strings.TrimSpace(*u.BaseURL)
if raw != "" {
parsed, err := url.Parse(raw)
if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Host == "" {
return nil, fmt.Errorf("API 地址必须是包含 https:// 或 http:// 的完整 URL")
}
}
hitl.AuditModel.BaseURL = raw
}
if u.APIKey != nil {
hitl.AuditModel.APIKey = strings.TrimSpace(*u.APIKey)
}
if u.Model != nil {
hitl.AuditModel.Model = strings.TrimSpace(*u.Model)
}
return &hitl, nil
}

View File

@ -0,0 +1,123 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/config"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestUpdateConfigHitlAuditModelSavesAndPreservesHitlSettings(t *testing.T) {
gin.SetMode(gin.TestMode)
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
raw := strings.Join([]string{
"openai:",
" provider: openai",
" base_url: https://api.deepseek.com/v1",
" api_key: main-secret",
" model: deepseek-chat",
"hitl:",
" audit_backend: openai",
" default_mode: approval",
" default_reviewer: audit_agent",
" tool_whitelist: [nmap, curl]",
" audit_agent_prompt: custom-approval-prompt",
" audit_model:",
" provider: openai_compatible",
" base_url: https://old-audit.example/v1",
" api_key: saved-audit-secret",
" model: old-audit-model",
" headers:",
" X-Audit-Gateway: fixture-header",
" reasoning:",
" profile: deepseek_compat",
"",
}, "\n")
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load(path)
if err != nil {
t.Fatal(err)
}
h := &ConfigHandler{configPath: path, config: cfg, logger: zap.NewNop()}
router := gin.New()
router.PUT("/config", h.UpdateConfig)
update := func(body string, wantStatus int) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodPut, "/config", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
if res.Code != wantStatus {
t.Fatalf("status = %d, want %d: %s", res.Code, wantStatus, res.Body.String())
}
var out map[string]any
_ = json.Unmarshal(res.Body.Bytes(), &out)
return out
}
// Update model and URL while keeping the masked audit key.
update(`{"hitl_audit_model":{"base_url":"https://api.deepseek.com/v1","api_key":"********","model":"deepseek-flash"}}`, http.StatusOK)
saved, err := config.Load(path)
if err != nil {
t.Fatal(err)
}
if saved.Hitl.AuditModel.Model != "deepseek-flash" || saved.Hitl.AuditModel.BaseURL != "https://api.deepseek.com/v1" {
t.Fatalf("audit model not updated: %+v", saved.Hitl.AuditModel)
}
if saved.Hitl.AuditModel.APIKey != "saved-audit-secret" {
t.Fatalf("masked audit key was not preserved: %q", saved.Hitl.AuditModel.APIKey)
}
if saved.Hitl.DefaultMode != "approval" || saved.Hitl.DefaultReviewer != "audit_agent" ||
len(saved.Hitl.ToolWhitelist) != 2 || saved.Hitl.AuditAgentPrompt != "custom-approval-prompt" ||
saved.Hitl.AuditModel.Headers["X-Audit-Gateway"] != "fixture-header" ||
saved.Hitl.AuditModel.Reasoning.Profile != "deepseek_compat" {
t.Fatalf("updating audit model overwrote unrelated hitl settings: %+v", saved.Hitl)
}
// Clearing api_key clears the saved audit key so chat mode inherits main model key.
update(`{"hitl_audit_model":{"provider":"","base_url":"","api_key":"","model":""}}`, http.StatusOK)
saved, err = config.Load(path)
if err != nil {
t.Fatal(err)
}
if saved.Hitl.AuditModel.APIKey != "" || saved.Hitl.AuditModel.Provider != "" || saved.Hitl.AuditModel.Model != "" {
t.Fatalf("expected cleared audit model fields, got %+v", saved.Hitl.AuditModel)
}
// Validation: TypeSafe requires an explicit key, invalid URL/backend/provider and hitl conflict fail with 400.
update(`{"hitl_audit_model":{"audit_backend":"typesafe"}}`, http.StatusBadRequest)
update(`{"hitl_audit_model":{"base_url":"not-a-url"}}`, http.StatusBadRequest)
update(`{"hitl_audit_model":{"audit_backend":"unknown"}}`, http.StatusBadRequest)
update(`{"hitl_audit_model":{"provider":"unknown"}}`, http.StatusBadRequest)
update(`{"hitl":{},"hitl_audit_model":{"model":"x"}}`, http.StatusBadRequest)
// Valid TypeSafe update persists.
update(`{"hitl_audit_model":{"audit_backend":"typesafe","api_key":"ts-secret","model":"jev-latest"}}`, http.StatusOK)
saved, err = config.Load(path)
if err != nil {
t.Fatal(err)
}
if saved.Hitl.AuditBackend != "typesafe" || saved.Hitl.AuditModel.APIKey != "ts-secret" {
t.Fatalf("typesafe update did not persist: %+v", saved.Hitl)
}
// Rollback on save failure leaves in-memory config unchanged.
h.configPath = filepath.Join(t.TempDir(), "missing-dir", "missing.yaml")
update(`{"hitl_audit_model":{"model":"unsaved-model"}}`, http.StatusInternalServerError)
if cfg.Hitl.AuditModel.Model != "jev-latest" {
t.Fatalf("failed save mutated in-memory audit model: %q", cfg.Hitl.AuditModel.Model)
}
}

View File

@ -12,11 +12,15 @@ import (
// TestAuditModelRequest overrides the saved audit model for this test only.
// Omitted fields retain their saved values; blank URL/model fields use the
// backend's normal defaults. Blank/masked keys retain the saved audit key.
// backend's normal defaults. Blank/masked keys retain the saved audit key
// unless ClearAPIKey explicitly clears it for inheritance testing.
type TestAuditModelRequest struct {
BaseURL *string `json:"base_url"`
APIKey *string `json:"api_key"`
Model *string `json:"model"`
AuditBackend *string `json:"audit_backend,omitempty"`
Provider *string `json:"provider,omitempty"`
BaseURL *string `json:"base_url"`
APIKey *string `json:"api_key"`
Model *string `json:"model"`
ClearAPIKey bool `json:"clear_api_key,omitempty"`
}
// TestAuditModel selects the protocol from the configured audit backend, using
@ -33,14 +37,27 @@ func (h *ConfigHandler) TestAuditModel(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "审计模型未配置"})
return
}
hitl, main := h.config.Hitl, h.config.OpenAI
hitl, main := cloneHitlConfig(h.config.Hitl), h.config.OpenAI
savedProvider, savedURL := hitl.AuditModel.Provider, hitl.AuditModel.BaseURL
if req.AuditBackend != nil {
hitl.AuditBackend = *req.AuditBackend
}
if req.Provider != nil {
hitl.AuditModel.Provider = strings.TrimSpace(*req.Provider)
}
if req.BaseURL != nil {
hitl.AuditModel.BaseURL = strings.TrimSpace(*req.BaseURL)
}
if probeHeaderProvider(hitl.AuditModel.Provider) != probeHeaderProvider(savedProvider) ||
probeHeaderURL(hitl.AuditModel.Provider, hitl.AuditModel.BaseURL) != probeHeaderURL(savedProvider, savedURL) {
hitl.AuditModel.Headers = nil
}
if req.Model != nil {
hitl.AuditModel.Model = strings.TrimSpace(*req.Model)
}
if req.APIKey != nil {
if req.ClearAPIKey {
hitl.AuditModel.APIKey = ""
} else if req.APIKey != nil {
if key := strings.TrimSpace(*req.APIKey); key != "" && key != maskedSecret {
hitl.AuditModel.APIKey = key
}

View File

@ -5080,9 +5080,12 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"base_url": map[string]interface{}{"type": "string", "description": "本次测试的 API 基地址,须包含 http:// 或 https://"},
"api_key": map[string]interface{}{"type": "string", "description": "本次测试的 API 密钥;空或 ******** 沿用已保存密钥"},
"model": map[string]interface{}{"type": "string", "description": "本次测试的模型"},
"audit_backend": map[string]interface{}{"type": "string", "description": "本次测试的审计后端(openai 或 typesafe),省略则沿用已保存值"},
"provider": map[string]interface{}{"type": "string", "description": "本次测试的聊天协议提供商(空字符串继承主模型,或 openai_compatible / claude)"},
"base_url": map[string]interface{}{"type": "string", "description": "本次测试的 API 基地址,须包含 http:// 或 https://"},
"api_key": map[string]interface{}{"type": "string", "description": "本次测试的 API 密钥;空或 ******** 沿用已保存密钥"},
"model": map[string]interface{}{"type": "string", "description": "本次测试的模型"},
"clear_api_key": map[string]interface{}{"type": "boolean", "description": "为 true 时按清除独立审计密钥(继承主模型密钥)测试"},
},
},
},

View File

@ -486,8 +486,7 @@
}
.chat-settings-fields { display: grid; gap: 16px; }
.chat-setting-field { display: grid; gap: 8px; min-width: 0; }
.chat-setting-reviewer { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); width: 100%; }
.chat-setting-reviewer .semi-radio-addon-buttonRadio { flex: 1; text-align: center; }
.chat-setting-reviewer { justify-self: start; width: fit-content; max-width: 100%; }
/* ---------- 侧滑面板 ---------- */

View File

@ -18,6 +18,10 @@ const PROVIDERS = [
{ value: 'openai_compatible', key: 'settingsProbe.compatible', fallback: '兼容 OpenAI 的接口' },
{ value: 'claude', key: 'settingsBasic.providerClaude', fallback: 'Claude(Anthropic Messages)' }
];
const AUDIT_BACKENDS = [
{ value: 'openai', key: 'settingsProbe.auditBackendChat', fallback: '对话模型' },
{ value: 'typesafe', key: 'settingsProbe.auditBackendTypeSafe', fallback: 'TypeSafe / Jev' }
];
const CONTEXT_PROFILES = ['', 'auto', 'local_auto', 'local', 'economy', 'custom'];
const TOKEN_LIMITS = [
['context_window', 'settingsBasic.contextWindow', '模型上下文窗口(Token)'],
@ -48,6 +52,15 @@ function numberValue(raw) {
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
}
function normalizeAuditProvider(raw) {
const value = (raw || '').trim();
const lower = value.toLowerCase();
if (!lower) return '';
if (lower === 'openai' || lower === 'openai_compatible') return 'openai_compatible';
if (lower === 'claude' || lower === 'anthropic') return 'claude';
return value;
}
function channelValues(channel) {
let provider = channel.provider || 'openai_compatible';
if (provider === 'openai') provider = 'openai_compatible';
@ -373,37 +386,125 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
context_profile: form.context_profile
});
// The server selects the configured audit backend and resolves inherited fields.
// Audit model configuration and connection probe (hitl.audit_backend + hitl.audit_model).
const auditBackendLabelId = useId();
const auditProviderLabelId = useId();
const auditModel = config.hitl?.audit_model || {};
const auditBackend = (config.hitl?.audit_backend || '').trim().toLowerCase();
const auditTypeSafe = ['typesafe', 'jev', 'type-safe', 'typesafe-ai'].includes(auditBackend);
const auditProvider = auditModel.provider?.trim() || config.openai?.provider || 'openai';
const rawAuditBackend = (config.hitl?.audit_backend || '').trim().toLowerCase();
const savedAuditTypeSafe = ['typesafe', 'jev', 'type-safe', 'typesafe-ai'].includes(rawAuditBackend);
const auditBaseline = {
audit_backend: savedAuditTypeSafe ? 'typesafe' : 'openai',
provider: normalizeAuditProvider(auditModel.provider),
base_url: auditModel.base_url || '',
api_key: auditModel.api_key || '',
model: auditModel.model || ''
};
const [auditDraft, setAuditDraft] = useState({});
const auditForm = { ...auditBaseline, ...auditDraft };
const auditDirty = Object.keys(auditDraft).length > 0;
const auditTypeSafe = auditForm.audit_backend === 'typesafe';
const auditProvider = auditForm.provider || config.openai?.provider || 'openai';
const auditClaude = ['claude', 'anthropic'].includes(auditProvider.toLowerCase());
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
const savedAuditProvider = auditModel.provider?.trim() || config.openai?.provider || 'openai';
const savedAuditProtocol = savedAuditTypeSafe ? 'TypeSafe / Jev'
: ['claude', 'anthropic'].includes(savedAuditProvider.toLowerCase()) ? 'Claude (Anthropic Messages)'
: t('settingsProbe.compatible', null, '兼容 OpenAI 的接口');
const auditSource = savedAuditTypeSafe || ['provider', 'base_url', 'api_key', 'model'].some(key => auditModel[key])
? auditModel.model || savedAuditProtocol
: 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({});
const auditForm = {
base_url: auditModel.base_url || '', api_key: auditModel.api_key || '', model: auditModel.model || '',
...auditDraft
};
const auditBackendOptions = AUDIT_BACKENDS.map(({ value, key, fallback }) => ({ value, label: t(key, null, fallback) }));
const auditProviderOptions = [
{ value: '', label: t('settingsProbe.auditInherit', null, '继承主模型') },
...PROVIDERS.map(({ value, key, fallback }) => ({ value, label: t(key, null, fallback) }))
];
if (auditForm.provider && !auditProviderOptions.some(option => option.value === auditForm.provider)) {
auditProviderOptions.push({ value: auditForm.provider, label: auditForm.provider });
}
const [auditState, setAuditState] = useState(EMPTY_PROBE);
const [auditBusy, setAuditBusy] = useState(false);
const [auditSaving, setAuditSaving] = useState(false);
const [auditSaveError, setAuditSaveError] = useState(null);
const [auditApplyPending, setAuditApplyPending] = useState(false);
const auditLocked = !canWrite || auditSaving || auditBusy;
useEffect(() => {
setAuditDraft({});
setAuditState(EMPTY_PROBE);
}, [auditBackend, auditProvider, auditModel.base_url, auditModel.api_key, auditModel.model]);
}, [auditBaseline.audit_backend, auditBaseline.provider, auditBaseline.base_url, auditBaseline.api_key, auditBaseline.model]);
const updateAudit = (field, value) => {
setAuditState(EMPTY_PROBE);
if (!auditApplyPending) setAuditSaveError(null);
setAuditDraft(current => {
const next = { ...current };
if (value === auditBaseline[field]) delete next[field];
else next[field] = value;
return next;
});
};
const discardAuditDraft = () => {
setAuditDraft({});
setAuditState(EMPTY_PROBE);
if (!auditApplyPending) setAuditSaveError(null);
};
const applyAudit = async message => {
try {
await api.post('/config/apply');
setAuditApplyPending(false);
toastSuccess(message);
} catch (error) {
setAuditApplyPending(true);
setAuditSaveError(error);
}
};
const saveAuditModel = async () => {
if (auditLocked || saving || !!busy || !auditDirty) return;
setAuditSaveError(null);
setAuditSaving(true);
try {
await api.put('/config', { hitl_audit_model: auditDraft });
setAuditDraft({});
await applyAudit(t('settingsProbe.auditModelSaved', null, '审计模型已保存'));
await reloadConfig({ silent: true });
} catch (error) {
setAuditSaveError(error);
} finally {
setAuditSaving(false);
}
};
const retryAuditApply = async () => {
if (auditLocked || saving || !!busy || !auditApplyPending) return;
setAuditSaving(true);
setAuditSaveError(null);
try {
await applyAudit(t('settings.apply.applySuccess', null, '配置已成功应用'));
} finally {
setAuditSaving(false);
}
};
const testAuditModel = async () => {
if (!canWrite) return;
if (auditLocked) return;
setAuditBusy(true);
setAuditState({ key: 'audit', payload: null, error: null });
const body = {
base_url: auditForm.base_url,
api_key: auditForm.api_key,
model: auditForm.model,
...(Object.hasOwn(auditDraft, 'audit_backend') ? { audit_backend: auditForm.audit_backend } : {}),
...(Object.hasOwn(auditDraft, 'provider') ? { provider: auditForm.provider } : {}),
...(auditBaseline.api_key !== '' && auditForm.api_key === '' ? { clear_api_key: true } : {})
};
try {
const payload = await api.post('/config/test-audit-model', auditForm);
const payload = await api.post('/config/test-audit-model', body);
setAuditState({ key: 'audit', payload, error: null });
} catch (error) {
setAuditState({ key: 'audit', payload: null, error });
@ -586,41 +687,110 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
<Space wrap spacing={8}>
<Text strong>{t('settingsProbe.auditModelTitle', null, '审计模型')}</Text>
<Text type="tertiary" size="small">{auditSource}</Text>
{auditDirty && (
<Tag size="small" color="amber">{t('settings.unsaved', null, '有未保存修改')}</Tag>
)}
</Space>
)}>
<div className="settings-probe-card">
<div><Tag size="small">{auditProtocol}</Tag></div>
{!auditTypeSafe && !auditForm.provider && (
<div><Tag size="small">{auditProtocol}</Tag></div>
)}
<Hint>
{auditTypeSafe
? t('settingsProbe.auditTypeSafeHint', null, '按已配置的 TypeSafe / Jev 后端测试。地址和模型留空使用 Jev 默认值;密钥沿用已保存的审计密钥,不继承主模型。')
: t('settingsProbe.auditChatHint', null, '按已配置的审计模型协议测试。地址和模型留空继承主模型;密钥留空或显示 ******** 时沿用已保存的审计密钥,未配置则继承主模型。')}
? t('settingsProbe.auditTypeSafeHint', null, '点击「保存审计模型」后生效。地址和模型留空使用 Jev 默认值;密钥必须独立配置,不继承主模型。')
: t('settingsProbe.auditChatHint', null, '点击「保存审计模型」后生效。地址、提供商和模型留空继承主模型;密钥显示 ******** 时沿用已保存的审计密钥,留空则继承主模型。')}
</Hint>
<div className="settings-probe-inline">
<div className="settings-field">
<Text id={auditBackendLabelId} type="tertiary" size="small">
{t('settingsProbe.auditBackendLabel', null, '审计后端')}
</Text>
<Select
value={auditForm.audit_backend}
onChange={value => updateAudit('audit_backend', value)}
optionList={auditBackendOptions}
aria-labelledby={auditBackendLabelId}
disabled={auditLocked}
style={{ width: '100%' }}
/>
</div>
{!auditTypeSafe && (
<div className="settings-field">
<Text id={auditProviderLabelId} type="tertiary" size="small">
{t('settingsBasic.apiProvider', null, 'API 提供商')}
</Text>
<Select
value={auditForm.provider}
onChange={value => updateAudit('provider', value)}
optionList={auditProviderOptions}
aria-labelledby={auditProviderLabelId}
disabled={auditLocked}
style={{ width: '100%' }}
/>
</div>
)}
{[
['base_url', 'baseUrl', 'API 地址', auditURLPlaceholder],
['api_key', 'apiKey', 'API 密钥', '********'],
[
'api_key',
'apiKey',
'API 密钥',
auditTypeSafe
? t('settingsProbe.auditKeyRequiredPlaceholder', null, '必填,不继承主模型')
: t('settingsProbe.auditKeyInheritPlaceholder', null, '留空继承主模型')
],
['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);
}}
onChange={value => updateAudit(field, value)}
placeholder={placeholder}
readOnly={!canWrite || auditBusy}
readOnly={auditLocked}
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}>
{(auditApplyPending || auditSaveError) && (
<div className="settings-channel-notices">
{auditApplyPending && (
<Banner type="warning" bordered closeIcon={null} description={(
<Space wrap>
{t('settingsProbe.auditSavedApplyFailed', null, '审计模型已写入配置,应用失败。')}
<Button size="small" disabled={auditLocked || saving || !!busy} onClick={retryAuditApply}>
{t('settingsProbe.retryApply', null, '重试应用')}
</Button>
</Space>
)} />
)}
<ErrorBanner error={auditSaveError} />
</div>
)}
<Space wrap>
{canWrite && (
<Button
size="small"
theme="solid"
type="primary"
loading={auditSaving}
disabled={!auditDirty || auditBusy || saving || !!busy}
onClick={saveAuditModel}
>
{t('settingsProbe.saveAuditModel', null, '保存审计模型')}
</Button>
)}
<Button size="small" loading={auditBusy} disabled={!canWrite || auditSaving} onClick={testAuditModel}>
{t('settingsProbe.testAuditModel', null, '测试审计模型')}
</Button>
{canWrite && auditDirty && (
<Button size="small" disabled={auditSaving || auditBusy} onClick={discardAuditDraft}>
{t('toolGuard.reset', null, '撤销修改')}
</Button>
)}
</Space>
<ProbeOutput state={auditState} />
</div>

View File

@ -9,7 +9,7 @@ async function openAuditCard(main) {
return section.locator('.settings-probe-card');
}
test.describe('audit model connection test', () => {
test.describe('audit model configuration and connection test', () => {
test.use({ appPermissions: [...UI_PERMISSIONS, 'config:write'] });
for (const entry of [
@ -29,6 +29,8 @@ test.describe('audit model connection test', () => {
await page.goto('/static/app/#/settings?section=models');
const main = await ready(page);
const card = await openAuditCard(main);
const save = card.getByRole('button', { name: '保存审计模型', exact: true });
await expect(save).toBeDisabled();
await expect(card.getByText(entry.protocol, { exact: true })).toBeVisible();
await expect(card.getByLabel('API 地址', { exact: true })).toHaveValue(entry.url);
await expect(card.getByLabel('API 密钥', { exact: true })).toHaveAttribute('type', 'password');
@ -41,8 +43,9 @@ test.describe('audit model connection test', () => {
['/api/config/test-audit-model', { base_url: entry.url, api_key: '********', model: entry.model }]
]);
// Form edits are transient test overrides and never save model settings.
// Form edits can be tested before saving without mutating server config until Save is clicked.
await card.getByLabel('模型', { exact: true }).fill('draft-model');
await expect(save).toBeEnabled();
await expect(card.getByText('连接成功', { exact: true })).toHaveCount(0);
mockApi.respond('POST', '/api/config/test-audit-model', { json: { success: false, error: 'API 返回错误 (HTTP 401): invalid credential', status_code: 401 } });
await card.getByRole('button', { name: '测试审计模型', exact: true }).click();
@ -51,14 +54,105 @@ test.describe('audit model connection test', () => {
expect(mockApi.writes()[1]).toMatchObject({ path: '/api/config/test-audit-model', body: { model: 'draft-model' } });
});
}
test('saves audit model edits, supports reset, and retries apply on failure', async ({ page, mockApi }) => {
const config = {
openai: mainModel,
tools: [],
hitl: { audit_backend: 'openai', audit_model: { provider: '', base_url: '', model: '', api_key: '' } }
};
mockApi.respond('GET', '/api/config', () => ({ json: config }));
mockApi.fail('PUT', '/api/config', '示例审计模型保存失败');
await page.goto('/static/app/#/settings?section=models');
const main = await ready(page);
const card = await openAuditCard(main);
const save = card.getByRole('button', { name: '保存审计模型', exact: true });
await expect(save).toBeDisabled();
// Fill fields and verify reset restores baseline.
await card.getByLabel('API 地址', { exact: true }).fill('https://api.deepseek.com/v1');
await card.getByLabel('API 密钥', { exact: true }).fill('sk-audit');
await card.getByLabel('模型', { exact: true }).fill('deepseek-flash');
const provider = card.getByRole('combobox', { name: 'API 提供商', exact: true });
await provider.click();
await page.getByRole('option').filter({ hasText: '兼容 OpenAI 的接口' }).click();
await expect(save).toBeEnabled();
await card.getByRole('button', { name: '撤销修改', exact: true }).click();
await expect(save).toBeDisabled();
await expect(card.getByLabel('模型', { exact: true })).toHaveValue('');
// Re-apply changes, hit save failure, then succeed with apply retry.
await card.getByLabel('API 地址', { exact: true }).fill('https://api.deepseek.com/v1');
await card.getByLabel('API 密钥', { exact: true }).fill('sk-audit');
await card.getByLabel('模型', { exact: true }).fill('deepseek-flash');
await provider.click();
await page.getByRole('option').filter({ hasText: '兼容 OpenAI 的接口' }).click();
await save.click();
await expect(card.getByText('示例审计模型保存失败', { exact: true })).toBeVisible();
await expect(save).toBeEnabled();
mockApi.respond('PUT', '/api/config', ({ body }) => {
const patch = body.hitl_audit_model;
if (patch.audit_backend !== undefined) config.hitl.audit_backend = patch.audit_backend;
Object.assign(config.hitl.audit_model, {
...(patch.provider !== undefined ? { provider: patch.provider } : {}),
...(patch.base_url !== undefined ? { base_url: patch.base_url } : {}),
...(patch.api_key !== undefined ? { api_key: patch.api_key ? '********' : '' } : {}),
...(patch.model !== undefined ? { model: patch.model } : {})
});
return { json: {} };
});
mockApi.fail('POST', '/api/config/apply', '示例审计配置应用失败');
await save.click();
await expect(save).toBeDisabled();
expect(mockApi.calls('PUT', '/api/config').at(-1).body).toEqual({
hitl_audit_model: {
provider: 'openai_compatible',
base_url: 'https://api.deepseek.com/v1',
api_key: 'sk-audit',
model: 'deepseek-flash'
}
});
const retry = card.getByRole('button', { name: '重试应用', exact: true });
await expect(retry).toBeEnabled();
mockApi.respond('POST', '/api/config/apply', { json: {} });
await retry.click();
await expect(retry).toHaveCount(0);
await expect(main.locator('.settings-audit-model').getByText('deepseek-flash', { exact: true })).toBeVisible();
});
});
test('audit model viewer cannot edit or start a test', async ({ page, mockApi }) => {
test('audit model viewer cannot edit, save, or start a test', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/config', { json: { openai: mainModel, tools: [] } });
await page.goto('/static/app/#/settings?section=models');
const main = await ready(page);
const card = await openAuditCard(main);
await expect(card.getByLabel('API 地址', { exact: true })).toHaveAttribute('readonly', '');
await expect(card.getByRole('button', { name: '保存审计模型', exact: true })).toHaveCount(0);
await expect(card.getByRole('button', { name: '测试审计模型', exact: true })).toBeDisabled();
expect(mockApi.writes()).toEqual([]);
});
test('chat HITL drawer reviewer segmented control keeps compact spacing', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/hitl/default-config', { json: {
defaultMode: 'approval', defaultReviewer: 'audit_agent', defaultTimeoutSeconds: 300, hitlGlobalToolWhitelist: ['tool_search']
} });
await page.goto('/static/app/#/chat');
const main = await ready(page);
await main.locator('.chat-composer-controls').getByRole('button', { name: '人机协同', exact: true }).click();
const dialog = page.getByRole('dialog').filter({ hasText: '人机协同' });
const group = dialog.locator('.chat-setting-reviewer');
const options = group.locator('.semi-radio');
await expect(options).toHaveCount(2);
const [firstBox, secondBox, groupBox] = await Promise.all([
options.nth(0).boundingBox(),
options.nth(1).boundingBox(),
group.boundingBox()
]);
expect(secondBox.x - (firstBox.x + firstBox.width)).toBeLessThanOrEqual(12);
expect(groupBox.width).toBeLessThan(260);
});

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.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-DdgOEYor.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=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)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{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)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{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)(l,{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)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.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{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.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-DpoRSPP9.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=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)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{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)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{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)(l,{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)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.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};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-DdgOEYor.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-DpoRSPP9.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};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-DdgOEYor.js";import"./c2-shared-YXtwoAM9.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-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-DpoRSPP9.js";import"./c2-shared-DX7U8sqg.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};

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

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.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-DdgOEYor.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,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)(a,{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)(o,{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)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{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{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.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-DpoRSPP9.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,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)(a,{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)(o,{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)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{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};

View File

@ -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-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-DdgOEYor.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-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-DpoRSPP9.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

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.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-DdgOEYor.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.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{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.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-DpoRSPP9.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.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

View File

@ -18,7 +18,7 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-DdgOEYor.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-DpoRSPP9.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-CHxO7u8f.js">

View File

@ -4771,7 +4771,15 @@
"imageReadSuccess": "تمت قراءة الصورة بنجاح",
"enableImageInput": "تفعيل الصور لهذه القناة",
"auditTitle": "اختبار اتصال نموذج التدقيق",
"auditTypeSafeHint": "يختبر خلفية TypeSafe / Jev المضبوطة. يستخدم العنوان والنموذج الفارغان قيم Jev الافتراضية. يستخدم المفتاح الفارغ أو المخفي مفتاح التدقيق المحفوظ ولا يرث مفتاح النموذج الرئيسي.",
"auditChatHint": "يختبر بروتوكول نموذج التدقيق المضبوط. يرث العنوان والنموذج الفارغان إعدادات النموذج الرئيسي. يستخدم المفتاح الفارغ أو المخفي مفتاح التدقيق المحفوظ، أو مفتاح النموذج الرئيسي إذا لم يُضبط مفتاح للتدقيق."
"auditTypeSafeHint": "اضغط على «حفظ نموذج التدقيق» لتطبيق التغييرات. يستخدم العنوان والنموذج الفارغان قيم Jev الافتراضية؛ يجب ضبط مفتاح تدقيق مستقل ولا يرث النموذج الرئيسي.",
"auditChatHint": "اضغط على «حفظ نموذج التدقيق» لتطبيق التغييرات. يرث العنوان والمزوّد والنموذج الفارغون النموذج الرئيسي؛ المفتاح ******** يحتفظ بالمفتاح المحفوظ، وتركه فارغاً يرث مفتاح النموذج الرئيسي.",
"auditBackendLabel": "خلفية التدقيق",
"auditBackendChat": "نموذج محادثة",
"auditBackendTypeSafe": "TypeSafe / Jev",
"auditKeyInheritPlaceholder": "اتركه فارغاً لوراثة النموذج الرئيسي",
"auditKeyRequiredPlaceholder": "مطلوب (لا يرث النموذج الرئيسي)",
"saveAuditModel": "حفظ نموذج التدقيق",
"auditModelSaved": "تم حفظ نموذج التدقيق",
"auditSavedApplyFailed": "تم حفظ نموذج التدقيق، لكن فشل تطبيق الإعدادات."
}
}

View File

@ -3189,8 +3189,16 @@
"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.",
"auditTypeSafeHint": "Save Audit Model applies your changes. Blank URL and model use Jev defaults. A separate audit key is required and never inherits the main model key.",
"auditChatHint": "Save Audit Model applies your changes. Blank URL, provider, and model inherit the main model. A key shown as ******** keeps the saved audit key; leaving it blank inherits the main model key.",
"auditBackendLabel": "Audit backend",
"auditBackendChat": "Chat model",
"auditBackendTypeSafe": "TypeSafe / Jev",
"auditKeyInheritPlaceholder": "Leave blank to inherit main model",
"auditKeyRequiredPlaceholder": "Required (not inherited)",
"saveAuditModel": "Save Audit Model",
"auditModelSaved": "Audit model saved",
"auditSavedApplyFailed": "The audit model was saved, but applying the configuration failed.",
"channelTitle": "Model Channels and Connection Tests",
"channelHelp": "Connection tests use the values in the form. Save Channel applies your changes. A key shown as ******** uses the saved credential.",
"saveChannel": "Save Channel",

View File

@ -5806,7 +5806,15 @@
"imageReadSuccess": "Изображение распознано",
"enableImageInput": "Включить изображения для этого канала",
"auditTitle": "Проверка подключения модели аудита",
"auditTypeSafeHint": "Проверяет настроенный TypeSafe / Jev. Пустые URL и модель используют значения Jev по умолчанию. Пустой или скрытый ключ берётся из настроек аудита; ключ основной модели не наследуется.",
"auditChatHint": "Проверяет протокол настроенной модели аудита. Пустые URL и модель наследуются от основной модели. Пустой или скрытый ключ использует сохранённый ключ аудита, а при его отсутствии — ключ основной модели."
"auditTypeSafeHint": "Нажмите «Сохранить модель аудита», чтобы применить изменения. Пустые URL и модель используют значения Jev по умолчанию; требуется отдельный ключ аудита.",
"auditChatHint": "Нажмите «Сохранить модель аудита», чтобы применить изменения. Пустые URL, провайдер и модель наследуют основную модель; ******** сохраняет текущий ключ аудита, пустое поле наследует основной ключ.",
"auditBackendLabel": "Бэкенд аудита",
"auditBackendChat": "Чат-модель",
"auditBackendTypeSafe": "TypeSafe / Jev",
"auditKeyInheritPlaceholder": "Оставьте пустым для наследования",
"auditKeyRequiredPlaceholder": "Обязательно (не наследуется)",
"saveAuditModel": "Сохранить модель аудита",
"auditModelSaved": "Модель аудита сохранена",
"auditSavedApplyFailed": "Модель аудита записана в конфигурацию, но применение не удалось."
}
}

View File

@ -3177,8 +3177,16 @@
"imageReadSuccess": "图片读取成功",
"enableImageInput": "为此通道启用图片",
"auditTitle": "审计模型连接测试",
"auditTypeSafeHint": "按已配置的 TypeSafe / Jev 后端测试。地址和模型留空使用 Jev 默认值;密钥沿用已保存的审计密钥,不继承主模型。",
"auditChatHint": "按已配置的审计模型协议测试。地址和模型留空继承主模型;密钥留空或显示 ******** 时沿用已保存的审计密钥,未配置则继承主模型。",
"auditTypeSafeHint": "点击「保存审计模型」后生效。地址和模型留空使用 Jev 默认值;密钥必须独立配置,不继承主模型。",
"auditChatHint": "点击「保存审计模型」后生效。地址、提供商和模型留空继承主模型;密钥显示 ******** 时沿用已保存的审计密钥,留空则继承主模型。",
"auditBackendLabel": "审计后端",
"auditBackendChat": "对话模型",
"auditBackendTypeSafe": "TypeSafe / Jev",
"auditKeyInheritPlaceholder": "留空继承主模型",
"auditKeyRequiredPlaceholder": "必填,不继承主模型",
"saveAuditModel": "保存审计模型",
"auditModelSaved": "审计模型已保存",
"auditSavedApplyFailed": "审计模型已写入配置,应用失败。",
"channelTitle": "模型通道与连接测试",
"channelHelp": "连接测试使用当前填写的值。点击「保存通道」后应用通道配置,显示 ******** 时沿用已保存的密钥。",
"saveChannel": "保存通道",