Files
superbrain/internal/ai/ai.go
T
Andrew S Erwin 167f74c6b4
release gate / check (push) Failing after 6m42s
Separate AI config from implementation: BYO provider, model and key per user
The plan matrix's 'use your own AI' rows, made real. internal/ai is now
pure implementation: three provider adapters — openai-compatible
(OpenRouter, OpenAI, Grok, Groq, Ollama, any house gateway), native
Anthropic (/v1/messages, x-api-key) and native Gemini (generateContent;
the key travels in the x-goog-api-key HEADER, never the URL, because Go's
HTTP error strings include URLs and errors get logged). One netguard-dialed
client, per-source outbound budgets (ai:user:<id> vs ai:server).

Configuration is data: UserAiConfig (migration 015) — one row per user
with provider, base URL, model and an API key encrypted at rest via
internal/crypto (the IMAP-password format), masked in every response; a
PUT echoing the mask or leaving the key blank keeps the stored value;
version contract on updates. New endpoints: GET/PUT/DELETE /api/ai/config,
POST /api/ai/test (one probe completion through the resolved config),
GET /api/ai/status (plan-gated availability, no secrets).

Resolution chain (ai.ResolveForUser): the user's enabled BYO config first
on EVERY plan; else the server env key (AI_API_KEY/AI_MODEL/AI_BASE_URL/
AI_PROVIDER) only when the tenant's plan may spend it — new
entitlements.AllowServerAI: premium (credits), core (house gateway) and
selfhosted (operator IS the user); free/standard are BYO-only, exactly the
matrix. No AI available => 428 with a pointer to Settings -> AI (was a
global 503): the precondition is per-user now. Agent compile and url_watch
extraction resolve per owner, so different users' tasks can run on
different providers.

Web: Settings -> AI tab (provider picker with per-provider defaults and
model hints, write-only key input, Test button, effective-source badge
with plan context, enable switch, remove). The Automations tab reads
/api/ai/status for a proactive banner and treats 428 as 'not configured'.

Preparatory refactors (behavior-preserving): agent.AutomationSchema
extracted as the single spec text shared by the compiler prompt (and the
upcoming chat assistant), and ai.CompleteMessages for multi-turn
conversations with per-provider role mapping (assistant -> model on
Gemini).

Tests: all three adapters against one loopback fake (asserting each
provider's auth-header shape), masked-key lifecycle incl. mask-echo
preservation across a provider switch, encrypted-at-rest verification,
plan gate both directions (free refuses the server key, premium/core/
selfhosted allow it), BYO precedence over the server key, validation
rejects, 428 paths, and compile resolution through a BYO config.
Full suite green (-race), converge green (015), web lint/SSR/build clean.

Docs: API.md AI section, RUNNING.md setup rewritten around BYO-first +
plan-gated server fallback, .env.example (AI_PROVIDER + the precedence
story), compose passthrough, AGENTS.md invariant (config vs
implementation, Gemini key-in-header rule).
2026-10-28 19:16:17 -05:00

451 lines
13 KiB
Go

// Package ai is the LLM gateway (AI features). Configuration is data,
// implementation is code:
//
// - IMPLEMENTATION: provider adapters (OpenAI-compatible — OpenRouter,
// OpenAI, Grok, Groq, Ollama, any house gateway — plus native Anthropic
// and Google Gemini), one shared netguard-dialed HTTP client, per-user
// outbound budgets, balanced-brace JSON extraction.
// - CONFIG: resolved per request via ResolveForUser — the user's own
// stored BYO config (UserAiConfig, key encrypted at rest) wins; the
// server env config (AI_API_KEY/AI_MODEL/AI_BASE_URL) is used only when
// the user's PLAN permits spending the operator's key
// (entitlements.AllowServerAI: premium/core/selfhosted — free and
// standard are bring-your-own-key, per the plan matrix).
//
// Rules: API keys live in env or encrypted rows, never in logs; provider
// error bodies are truncated before surfacing (they can reflect keys);
// model output is never trusted — callers parse via ExtractJSON + schema
// validation (see internal/agent).
package ai
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
crypt "github.com/andrew/superbrain/internal/crypto"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/entitlements"
"github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/superbrain/internal/outbound"
)
// DefaultModel is the fallback for the server env config (OpenRouter free
// tier). User configs always carry an explicit model.
const DefaultModel = "recursive/flint-v1.0:free"
const defaultOpenAIBase = "https://openrouter.ai/api/v1"
// Providers (UserAiConfig.provider CHECK mirrors this list).
const (
ProviderOpenAICompatible = "openai-compatible"
ProviderAnthropic = "anthropic"
ProviderGemini = "gemini"
)
func ValidProvider(p string) bool {
switch p {
case ProviderOpenAICompatible, ProviderAnthropic, ProviderGemini:
return true
}
return false
}
// ErrNoAI means neither a user BYO config nor a plan-permitted server key
// is available. Callers answer 428 with a pointer to Settings → AI.
var ErrNoAI = errors.New("ai: no configuration available for this user")
// Resolved is one usable endpoint. Source is "user" (BYO) or "server"
// (env); it feeds budget keys and the status endpoint, never prompts.
type Resolved struct {
Provider string
BaseURL string
Model string
APIKey string
Source string
UserID string
}
// client dials through netguard for every provider (public ranges +
// 443/80 unless the operator pinned the host or allowed private ranges).
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,
},
}
// ServerConfigured reports whether the env-level gateway is set (used by
// the status endpoint; whether a user may USE it is a plan question).
func ServerConfigured() bool { return strings.TrimSpace(os.Getenv("AI_API_KEY")) != "" }
func serverConfig() (Resolved, bool) {
key := strings.TrimSpace(os.Getenv("AI_API_KEY"))
if key == "" {
return Resolved{}, false
}
model := strings.TrimSpace(os.Getenv("AI_MODEL"))
if model == "" {
model = DefaultModel
}
base := strings.TrimRight(strings.TrimSpace(os.Getenv("AI_BASE_URL")), "/")
provider := strings.TrimSpace(os.Getenv("AI_PROVIDER"))
if provider == "" {
provider = ProviderOpenAICompatible
}
if base == "" {
switch provider {
case ProviderAnthropic:
base = "https://api.anthropic.com"
case ProviderGemini:
base = "https://generativelanguage.googleapis.com"
default:
base = defaultOpenAIBase
}
}
return Resolved{Provider: provider, BaseURL: base, Model: model, APIKey: key, Source: "server"}, true
}
// ResolveForUser applies the resolution chain: the user's enabled BYO
// config first, then the server key iff the user's plan may spend it.
func ResolveForUser(ctx context.Context, d *db.DB, userID string) (Resolved, error) {
var id, provider, baseURL, model, encKey string
var enabled bool
err := d.QueryRowContext(ctx,
`SELECT id, provider, "baseUrl", model, "apiKey", enabled FROM "UserAiConfig" WHERE "ownerId"=$1`,
userID).Scan(&id, &provider, &baseURL, &model, &encKey, &enabled)
if err == nil && enabled && encKey != "" {
key, decErr := crypt.Decrypt(encKey, config.Load().EncryptionSecret())
if decErr != nil {
return Resolved{}, fmt.Errorf("ai: stored key cannot be decrypted; re-enter it in Settings: %w", decErr)
}
return Resolved{
Provider: provider, BaseURL: strings.TrimRight(baseURL, "/"),
Model: model, APIKey: key, Source: "user", UserID: userID,
}, nil
}
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return Resolved{}, err
}
// Plan gate on the OPERATOR's key: free/standard tenants are BYO-only
// (entitlements.AllowServerAI), so a hosted instance never silently
// burns house credits for plans that promise "use your own AI".
var tenantID *string
if e := d.QueryRowContext(ctx, `SELECT "tenantId" FROM "User" WHERE id=$1`, userID).Scan(&tenantID); e != nil {
return Resolved{}, e
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
plan, e := db.NewTenantRepo(d).Plan(ctx, tid)
if e != nil {
return Resolved{}, e
}
if r, ok := serverConfig(); ok && entitlements.AllowServerAI(plan) {
r.UserID = userID
return r, nil
}
return Resolved{}, ErrNoAI
}
// Message is one chat turn. Roles are normalized ("assistant" is accepted
// and mapped per provider, e.g. Gemini's "model").
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
// Complete sends one system+user exchange through a resolved endpoint.
func Complete(ctx context.Context, r Resolved, system, user string) (string, error) {
return CompleteMessages(ctx, r, system, []Message{{Role: "user", Content: user}})
}
// CompleteMessages sends a multi-turn conversation with a server-owned
// system prompt. Callers cap the message count/size before calling.
func CompleteMessages(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
if r.APIKey == "" {
return "", ErrNoAI
}
if len(msgs) == 0 {
return "", errors.New("ai: no messages")
}
// Per-user (BYO) or shared (server) budget: a slow provider must not
// pile up goroutines either way.
budgetKey := "ai:server"
if r.Source == "user" {
budgetKey = "ai:user:" + r.UserID
}
release, _, ok := outbound.Reserve(budgetKey, 10, time.Minute)
if !ok {
return "", errors.New("ai: busy, try again shortly")
}
defer release()
switch r.Provider {
case ProviderAnthropic:
return completeAnthropic(ctx, r, system, msgs)
case ProviderGemini:
return completeGemini(ctx, r, system, msgs)
default:
return completeOpenAI(ctx, r, system, msgs)
}
}
func completeOpenAI(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
all := make([]map[string]string, 0, len(msgs)+1)
all = append(all, map[string]string{"role": "system", "content": system})
for _, m := range msgs {
role := m.Role
if role != "assistant" && role != "user" {
role = "user"
}
all = append(all, map[string]string{"role": role, "content": m.Content})
}
payload, err := json.Marshal(map[string]any{"model": r.Model, "messages": all})
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/chat/completions", bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+r.APIKey)
body, status, err := do(req)
if err != nil {
return "", err
}
if status != 200 {
return "", providerError(status, body)
}
var out struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `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
}
func completeAnthropic(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
all := make([]map[string]string, 0, len(msgs))
for _, m := range msgs {
role := m.Role
if role != "assistant" && role != "user" {
role = "user"
}
all = append(all, map[string]string{"role": role, "content": m.Content})
}
payload, err := json.Marshal(map[string]any{
"model": r.Model,
"max_tokens": 1024,
"system": system,
"messages": all,
})
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/v1/messages", bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", r.APIKey)
req.Header.Set("anthropic-version", "2023-06-01")
body, status, err := do(req)
if err != nil {
return "", err
}
if status != 200 {
return "", providerError(status, body)
}
var out struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
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))
}
var text string
for _, c := range out.Content {
if c.Type == "text" {
text += c.Text
}
}
if text == "" {
return "", errors.New("ai: provider returned no text")
}
return text, nil
}
func completeGemini(ctx context.Context, r Resolved, system string, msgs []Message) (string, error) {
contents := make([]map[string]any, 0, len(msgs))
for _, m := range msgs {
role := "user"
if m.Role == "assistant" {
role = "model"
}
contents = append(contents, map[string]any{
"role": role,
"parts": []map[string]string{{"text": m.Content}},
})
}
payload, err := json.Marshal(map[string]any{
"system_instruction": map[string]any{"parts": []map[string]string{{"text": system}}},
"contents": contents,
})
if err != nil {
return "", err
}
// The key travels in a HEADER (x-goog-api-key), never the URL: Go's HTTP
// error strings include the full URL, and errors get logged.
endpoint := fmt.Sprintf("%s/v1beta/models/%s:generateContent", r.BaseURL, url.PathEscape(r.Model))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-goog-api-key", r.APIKey)
body, status, err := do(req)
if err != nil {
return "", err
}
if status != 200 {
return "", providerError(status, body)
}
var out struct {
Candidates []struct {
Content struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"content"`
} `json:"candidates"`
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))
}
var text string
if len(out.Candidates) > 0 {
for _, p := range out.Candidates[0].Content.Parts {
text += p.Text
}
}
if text == "" {
return "", errors.New("ai: provider returned no text")
}
return text, nil
}
func do(req *http.Request) ([]byte, int, error) {
res, err := client.Do(req)
if err != nil {
return nil, 0, err
}
defer res.Body.Close()
body, err := io.ReadAll(io.LimitReader(res.Body, 4<<20))
return body, res.StatusCode, err
}
// providerError never echoes the full body: provider errors can reflect
// account details or the request's Authorization context.
func providerError(status int, body []byte) error {
return fmt.Errorf("ai: provider answered %d: %s", status, truncate(string(body), 200))
}
// 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 {
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])
}