// Package ai is the LLM gateway (AI features phase 1). One OpenAI-compatible // chat-completions client pointed at OpenRouter by default; any // OpenAI-compatible endpoint works via AI_BASE_URL (house Core gateway, // Ollama, etc.). // // Rules this package exists to enforce: // - the API key lives ONLY in env (.env), never in the repo or logs; // - every dial goes through netguard + an outbound budget, like all // server-initiated work; // - model output is never trusted: callers parse it through // ExtractJSON + schema validation (see internal/agent). package ai import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "os" "strings" "time" "github.com/andrew/superbrain/internal/netguard" "github.com/andrew/superbrain/internal/outbound" ) // DefaultModel is the phase-1 free OpenRouter model. Override with AI_MODEL. const DefaultModel = "recursive/flint-v1.0:free" const defaultBaseURL = "https://openrouter.ai/api/v1" // ErrNotConfigured means AI_API_KEY is unset; callers answer 503 (a global // deployment property, not a per-user signal). var ErrNotConfigured = errors.New("ai: not configured (AI_API_KEY is unset)") type Config struct { APIKey string Model string BaseURL string } func LoadConfig() Config { model := strings.TrimSpace(os.Getenv("AI_MODEL")) if model == "" { model = DefaultModel } base := strings.TrimSpace(os.Getenv("AI_BASE_URL")) if base == "" { base = defaultBaseURL } return Config{APIKey: strings.TrimSpace(os.Getenv("AI_API_KEY")), Model: model, BaseURL: strings.TrimRight(base, "/")} } func Configured() bool { return LoadConfig().APIKey != "" } // client dials through netguard (public ranges + 443/80 only unless the // operator pinned the host or allowed private ranges) — the AI endpoint is // operator-configured, but the discipline is uniform for every server dial. var client = &http.Client{ Timeout: 90 * time.Second, Transport: &http.Transport{ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { if netguard.AllowPrivate() { return netguard.DialContext(ctx, network, address) } return netguard.DialContextPorts(ctx, network, address, 80, 443) }, IdleConnTimeout: 30 * time.Second, MaxIdleConns: 8, MaxIdleConnsPerHost: 4, }, } type chatMessage struct { Role string `json:"role"` Content string `json:"content"` } // Complete sends one system+user exchange and returns the assistant text. // Bounded by the shared outbound budget so a slow provider cannot pile up // goroutines. func Complete(ctx context.Context, system, user string) (string, error) { cfg := LoadConfig() if cfg.APIKey == "" { return "", ErrNotConfigured } release, _, ok := outbound.Reserve("ai", 10, time.Minute) if !ok { return "", errors.New("ai: busy, try again shortly") } defer release() payload, err := json.Marshal(map[string]any{ "model": cfg.Model, "messages": []chatMessage{ {Role: "system", Content: system}, {Role: "user", Content: user}, }, }) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.BaseURL+"/chat/completions", bytes.NewReader(payload)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+cfg.APIKey) res, err := client.Do(req) if err != nil { return "", err } defer res.Body.Close() body, err := io.ReadAll(io.LimitReader(res.Body, 2<<20)) if err != nil { return "", err } if res.StatusCode != 200 { // Never echo the response body wholesale: it can reflect the key or // account details. Status + a short prefix is enough to debug. return "", fmt.Errorf("ai: provider answered %d: %s", res.StatusCode, truncate(string(body), 200)) } var out struct { Choices []struct { Message chatMessage `json:"message"` } `json:"choices"` Error *struct { Message string `json:"message"` } `json:"error"` } if err := json.Unmarshal(body, &out); err != nil { return "", fmt.Errorf("ai: unreadable provider response: %w", err) } if out.Error != nil { return "", fmt.Errorf("ai: provider error: %s", truncate(out.Error.Message, 200)) } if len(out.Choices) == 0 { return "", errors.New("ai: provider returned no choices") } return out.Choices[0].Message.Content, nil } // ExtractJSON pulls the first balanced JSON object out of a model reply // (models wrap JSON in prose or code fences despite instructions). func ExtractJSON(s string) (json.RawMessage, error) { if i := strings.Index(s, "```"); i >= 0 { // Prefer a fenced block when present. rest := s[i+3:] if j := strings.Index(rest, "```"); j > 0 { s = rest[:j] } } start := strings.Index(s, "{") if start < 0 { return nil, errors.New("ai: no JSON object in model reply") } depth := 0 inStr := false esc := false for i := start; i < len(s); i++ { c := s[i] switch { case inStr: if esc { esc = false } else if c == '\\' { esc = true } else if c == '"' { inStr = false } case c == '"': inStr = true case c == '{': depth++ case c == '}': depth-- if depth == 0 { return json.RawMessage(s[start : i+1]), nil } } } return nil, errors.New("ai: unbalanced JSON in model reply") } func truncate(s string, n int) string { rs := []rune(s) if len(rs) <= n { return s } return string(rs[:n]) }