Files
logan 2336c9433c feat(ai): Agent SSE + Anthropic/responses tools + P1 确认写
- Agent 支持 SSE(步骤边推、正文分块),JSON 非流式 fallback
- tool calling 覆盖 openai-chat / anthropic / responses(单测解析回灌)
- P1:mcp.json mode=read_write 才可写;需 confirm_danger;Agent 剥离模型自带令牌
- GET /api/ai/mcp-status、POST /api/ai/agent/confirm;审计 source=mcp|agent
2026-10-15 13:00:40 +08:00

101 lines
2.4 KiB
Go

package ai
import (
"encoding/json"
"os"
"path/filepath"
"strings"
)
// Config AI 配置;provider 为预设 id(stub|openai|deepseek|anthropic|ollama|custom…),
// protocol/authStyle/allowInsecureHTTP 决定远端调用行为(见 remote.go)。
type Config struct {
Provider string `json:"provider"`
BaseURL string `json:"baseURL"`
APIKey string `json:"apiKey,omitempty"`
Model string `json:"model"`
Protocol string `json:"protocol,omitempty"`
AuthStyle string `json:"authStyle,omitempty"`
AllowInsecureHTTP bool `json:"allowInsecureHttp,omitempty"`
}
func configPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".opsxdb", "ai.json"), nil
}
// LoadConfig 读取配置:~/.opsxdb/ai.json 优先,env(OPSXDB_AI_*)兜底逐字段补充。
func LoadConfig() Config {
cfg := Config{
Provider: strings.TrimSpace(os.Getenv("OPSXDB_AI_PROVIDER")),
BaseURL: strings.TrimSpace(os.Getenv("OPSXDB_AI_BASE_URL")),
APIKey: strings.TrimSpace(os.Getenv("OPSXDB_AI_API_KEY")),
Model: strings.TrimSpace(os.Getenv("OPSXDB_AI_MODEL")),
}
if p, err := configPath(); err == nil {
if b, err := os.ReadFile(p); err == nil {
var f Config
if json.Unmarshal(b, &f) == nil {
if f.Provider != "" {
cfg.Provider = f.Provider
}
if f.BaseURL != "" {
cfg.BaseURL = f.BaseURL
}
if f.APIKey != "" {
cfg.APIKey = f.APIKey
}
if f.Model != "" {
cfg.Model = f.Model
}
if f.Protocol != "" {
cfg.Protocol = f.Protocol
}
if f.AuthStyle != "" {
cfg.AuthStyle = f.AuthStyle
}
cfg.AllowInsecureHTTP = f.AllowInsecureHTTP
}
}
}
if cfg.Provider == "" {
if cfg.APIKey != "" {
cfg.Provider = "openai"
} else {
cfg.Provider = "stub"
}
}
return cfg
}
// SaveConfig 写 ~/.opsxdb/ai.json(0600,与本机 token 同威胁模型)。
func SaveConfig(c Config) error {
p, err := configPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
return err
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
return os.WriteFile(p, b, 0600)
}
// MaskedKey 返回脱敏后的 key 展示形式(sk-***)。
func (c Config) MaskedKey() string {
k := c.APIKey
if k == "" {
return ""
}
if len(k) <= 6 {
return "***"
}
return k[:3] + "***"
}