Separate AI config from implementation: BYO provider, model and key per user
release gate / check (push) Failing after 6m42s

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).
This commit is contained in:
Andrew S Erwin
2026-10-28 19:16:17 -05:00
parent 19531cf8b9
commit 167f74c6b4
18 changed files with 1188 additions and 126 deletions
+7 -1
View File
@@ -5,11 +5,12 @@ import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Check, X, AlertTriangle } from 'lucide-react'
import { User, Mail, Server, Cloud, Shield, Bell, Sparkles, Bot, Check, X, AlertTriangle } from 'lucide-react'
import { toast } from 'sonner'
import { invalidateReference } from '@/lib/reference-data'
import { NotificationsSettings } from '@/components/notifications-settings'
import { AutomationsSettings } from '@/components/automations-settings'
import { AiSettings } from '@/components/ai-settings'
import type { OidcStatus } from '@/lib/oidc-config'
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
@@ -99,6 +100,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
<TabsTrigger value="nextcloud" className="gap-1.5"><Cloud className="h-3.5 w-3.5" /> Nextcloud</TabsTrigger>
<TabsTrigger value="notifications" className="gap-1.5"><Bell className="h-3.5 w-3.5" /> Notifications</TabsTrigger>
<TabsTrigger value="automations" className="gap-1.5"><Sparkles className="h-3.5 w-3.5" /> Automations</TabsTrigger>
<TabsTrigger value="ai" className="gap-1.5"><Bot className="h-3.5 w-3.5" /> AI</TabsTrigger>
<TabsTrigger value="oidc" className="gap-1.5"><Shield className="h-3.5 w-3.5" /> OIDC</TabsTrigger>
</TabsList>
@@ -184,6 +186,10 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
<AutomationsSettings />
</TabsContent>
<TabsContent value="ai" className="space-y-4 mt-4">
<AiSettings />
</TabsContent>
<TabsContent value="oidc" className="space-y-4 mt-4">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> OIDC Configuration</h3>
+220
View File
@@ -0,0 +1,220 @@
'use client'
// Settings → AI: per-user BYO provider configuration. Config is data
// (UserAiConfig row), implementation is server-side adapters — the UI only
// ever sees masked keys and the resolved availability status. The server
// key (operator env) shows as a fallback the user's plan may or may not
// include; the UI never learns whether the key itself exists beyond that.
import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Bot, Loader2, Trash2, PlugZap } from 'lucide-react'
import { toast } from 'sonner'
const KEY_MASK = '••••••••'
type AiConfig = {
id: string; provider: string; baseUrl: string; model: string
apiKey: string; enabled: boolean; version: number
}
type AiStatus = {
userConfigured: boolean; userEnabled: boolean
serverAvailable: boolean; effective: string; plan: string
}
const PROVIDERS: Record<string, { label: string; defaultBase: string; modelHint: string }> = {
'openai-compatible': {
label: 'OpenAI-compatible (OpenRouter, OpenAI, Grok, Groq, Ollama, …)',
defaultBase: 'https://openrouter.ai/api/v1',
modelHint: 'e.g. recursive/flint-v1.0:free or gpt-4o-mini',
},
anthropic: { label: 'Anthropic (Claude)', defaultBase: 'https://api.anthropic.com', modelHint: 'e.g. claude-sonnet-4-5' },
gemini: { label: 'Google Gemini', defaultBase: 'https://generativelanguage.googleapis.com', modelHint: 'e.g. gemini-2.0-flash' },
}
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function AiSettings() {
const [config, setConfig] = useState<AiConfig | null>(null)
const [status, setStatus] = useState<AiStatus | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [testing, setTesting] = useState(false)
const [provider, setProvider] = useState('openai-compatible')
const [baseUrl, setBaseUrl] = useState('')
const [model, setModel] = useState('')
const [apiKey, setApiKey] = useState('')
// Promise-chain loading (house pattern: no synchronous setState in
// effects — the SSR lint refuses cascading renders).
const reload = useCallback(() =>
Promise.all([
api('/api/ai/config').then(r => r.json()),
api('/api/ai/status').then(r => r.json()),
])
.then(([cfg, st]) => {
if (cfg && typeof cfg === 'object' && cfg.id) {
setConfig(cfg)
setProvider(cfg.provider)
setBaseUrl(cfg.baseUrl ?? '')
setModel(cfg.model ?? '')
setApiKey('') // never prefill secrets; empty keeps the stored key
} else {
setConfig(null)
}
if (st && typeof st === 'object') setStatus(st)
})
.catch(() => { toast.error('Could not load AI settings') })
.finally(() => { setLoading(false) }), [])
useEffect(() => { reload() }, [reload])
const save = async () => {
if (!model.trim()) { toast.error('Model is required'); return }
if (!config && !apiKey.trim()) { toast.error('API key is required'); return }
setSaving(true)
try {
const body: Record<string, unknown> = {
provider,
baseUrl: baseUrl.trim() || PROVIDERS[provider].defaultBase,
model: model.trim(),
// Empty input on an existing config keeps the stored key (same
// write-only contract as the mask).
apiKey: apiKey.trim() || (config ? KEY_MASK : ''),
}
if (config) body.version = config.version
const res = await api('/api/ai/config', { method: 'PUT', body: JSON.stringify(body) })
if (res.ok) {
toast.success('AI settings saved')
setApiKey('')
await reload()
} else {
const data = await res.json().catch(() => null)
toast.error(data?.error ?? 'Could not save AI settings')
}
} finally { setSaving(false) }
}
const test = async () => {
setTesting(true)
try {
const res = await api('/api/ai/test', { method: 'POST' })
const data = await res.json().catch(() => null)
if (res.ok) {
toast.success(`AI reachable via ${data?.source === 'user' ? 'your key' : 'the server key'} (${data?.model}): “${data?.reply}”`)
} else {
toast.error(data?.error ?? 'AI test failed')
}
} finally { setTesting(false) }
}
const remove = async () => {
const res = await api('/api/ai/config', { method: 'DELETE' })
if (res.ok) {
toast.success('Your AI key was removed')
setConfig(null); setApiKey(''); setModel(''); setBaseUrl('')
await reload()
} else {
const data = await res.json().catch(() => null)
toast.error(data?.error ?? 'Could not remove the config')
}
}
const toggleEnabled = async (enabled: boolean) => {
if (!config) return
const res = await api('/api/ai/config', {
method: 'PUT',
body: JSON.stringify({
provider: config.provider, baseUrl: config.baseUrl, model: config.model,
apiKey: KEY_MASK, enabled, version: config.version,
}),
})
if (res.ok) await reload()
else {
const data = await res.json().catch(() => null)
toast.error(data?.error ?? 'Could not update')
}
}
if (loading) {
return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading AI settings…</div>
}
return (
<div className="space-y-6">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Bot className="h-4 w-4" /> Your AI provider</h3>
<p className="text-xs text-muted-foreground">
Superbrain uses AI for <strong>Automations</strong> (compiling “hey superbrain” requests and
reading watched pages). Bring your own provider and key — it is stored encrypted, never
shown again, and used only for your requests.
{status?.serverAvailable
? ' This server also provides a shared AI key included in your plan; your own key takes precedence.'
: ' Your plan is bring-your-own-key, so automations need a key here.'}
</p>
<div className="flex items-center gap-2 text-xs">
<span className="text-muted-foreground">Effective source:</span>
<Badge variant={status?.effective === 'none' ? 'destructive' : 'default'}>
{status?.effective === 'user' ? 'your key' : status?.effective === 'server' ? 'server key (plan)' : 'none — AI features disabled'}
</Badge>
{config && (
<span className="ml-auto flex items-center gap-2">
<span className="text-muted-foreground">Enabled</span>
<Switch checked={config.enabled} onCheckedChange={(v: boolean) => toggleEnabled(v)} aria-label="Enable AI config" />
</span>
)}
</div>
<div className="space-y-2 border-t pt-3">
<Select value={provider} onValueChange={(v: string) => { setProvider(v); setBaseUrl('') }}>
<SelectTrigger aria-label="Provider"><SelectValue /></SelectTrigger>
<SelectContent>
{Object.entries(PROVIDERS).map(([k, p]) => (
<SelectItem key={k} value={k}>{p.label}</SelectItem>
))}
</SelectContent>
</Select>
<Input
placeholder={`Base URL (blank = ${PROVIDERS[provider].defaultBase})`}
value={baseUrl}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBaseUrl(e.target.value)}
aria-label="Base URL"
/>
<Input
placeholder={`Model — ${PROVIDERS[provider].modelHint}`}
value={model}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setModel(e.target.value)}
aria-label="Model"
/>
<Input
type="password"
placeholder={config ? 'API key (leave blank to keep the current key)' : 'API key'}
value={apiKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setApiKey(e.target.value)}
aria-label="API key"
autoComplete="off"
/>
<div className="flex gap-2">
<Button size="sm" onClick={save} loading={saving}>{config ? 'Save changes' : 'Save AI settings'}</Button>
<Button size="sm" variant="outline" onClick={test} loading={testing} className="gap-1.5">
<PlugZap className="h-3.5 w-3.5" /> Test
</Button>
{config && (
<Button size="sm" variant="ghost" onClick={remove} className="gap-1.5 text-muted-foreground">
<Trash2 className="h-3.5 w-3.5" /> Remove my key
</Button>
)}
</div>
</div>
</div>
</div>
)
}
+8 -5
View File
@@ -44,7 +44,6 @@ export function AutomationsSettings() {
const [channels, setChannels] = useState<ChannelOption[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
// Composer state
const [text, setText] = useState('')
const [compiling, setCompiling] = useState(false)
@@ -57,11 +56,13 @@ export function AutomationsSettings() {
api('/api/agent/tasks').then(r => r.json()),
api('/api/agent/runs').then(r => r.json()),
api('/api/notifications/channels').then(r => r.json()),
api('/api/ai/status').then(r => r.json()).catch(() => null),
])
.then(([tk, rn, ch]) => {
.then(([tk, rn, ch, st]) => {
if (Array.isArray(tk)) setTasks(tk)
if (Array.isArray(rn)) setRuns(rn.slice(0, 10))
if (Array.isArray(ch)) setChannels(ch)
if (st && typeof st === 'object') setAvailable(st.effective !== 'none')
})
.catch(() => { toast.error('Could not load automations') })
.finally(() => { setLoading(false) }), [])
@@ -74,7 +75,7 @@ export function AutomationsSettings() {
const data = await res.json()
if (data?.error) msg = data.error
} catch { /* non-JSON body */ }
if (res.status === 503) setAvailable(false)
if (res.status === 428) setAvailable(false)
toast.error(msg)
return msg
}
@@ -167,8 +168,10 @@ export function AutomationsSettings() {
</p>
{!available && (
<p className="text-xs text-destructive">
AI is not configured on this server (AI_API_KEY missing), so compilation is unavailable.
Tasks with signal conditions still run.
No AI is available to you yet — open the <strong>AI</strong> tab in Settings and add
your own provider and API key{` `}
(or your plan may include the server-provided key once the operator enables it).
Signal-condition tasks run without AI.
</p>
)}
<Textarea