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
+35 -22
View File
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/andrew/superbrain/internal/ai"
"github.com/andrew/superbrain/internal/db"
)
// ErrCompileRejected means the model could not (or refused to) express the
@@ -16,17 +17,11 @@ type ErrCompileRejected struct{ Reason string }
func (e *ErrCompileRejected) Error() string { return "compile rejected: " + e.Reason }
// compileSystem is the compiler contract. The model gets a closed schema,
// worked examples, and an explicit refusal path — it never gets to invent
// actions. Everything it returns is re-validated by ValidateSpec; the
// prompt is convenience, the validator is the boundary.
const compileSystem = `You are Superbrain's automation compiler. Convert the user's request into ONE automation task, or refuse.
Reply with ONLY a JSON object, no prose:
{"name": "<short task name>", "spec": <Spec>} on success
{"error": "<one sentence, user-facing>"} when the request cannot be expressed.
Spec schema:
// AutomationSchema is the shared contract text describing the task spec,
// the closed action set and the refusal rules. BOTH the compile prompt and
// the chat assistant prompt embed it, so the two surfaces can never drift
// on what an automation is.
const AutomationSchema = `Spec schema:
{
"condition": {
"type": "url_watch" | "signal",
@@ -60,22 +55,36 @@ What Superbrain can actually do — anything else MUST be refused:
- Actions: notify (an existing channel), email (one message to one fixed
recipient), bookmark (save one URL for the user).
Examples:
- "when the denver-indy round trip on https://flights.example/q/123 drops below 400, email david@email.com" ->
{"name":"Flights DEN-IND under $400","spec":{"condition":{"type":"url_watch","url":"https://flights.example/q/123","question":"What is the cheapest round-trip flight price shown, in USD?","op":"lt","threshold":400},"action":{"type":"email","channelId":"","to":"david@email.com","title":"Flight deal: DEN-IND under $400","body":"A round-trip flight dropped below $400."},"pollMinutes":60,"once":true}}
- "tell me when my inbox gets an invoice" ->
{"name":"Invoice signals","spec":{"condition":{"type":"signal","keyword":"invoice"},"action":{"type":"notify","channelId":""},"pollMinutes":15,"once":false}}
- "book me a hotel" -> {"error":"Superbrain cannot book anything; it can watch a public page and notify you."}
Rules: prefer once=true for deals and once=false for ongoing watches;
pollMinutes>=15 (60 unless the user asks for faster); never invent URLs the
user did not provide — if a watch target is missing, refuse and ask for it;
keep names under 80 characters.`
// compileSystem is the compiler contract. The model gets a closed schema,
// worked examples, and an explicit refusal path — it never gets to invent
// actions. Everything it returns is re-validated by ValidateSpec; the
// prompt is convenience, the validator is the boundary.
const compileSystem = `You are Superbrain's automation compiler. Convert the user's request into ONE automation task, or refuse.
Reply with ONLY a JSON object, no prose:
{"name": "<short task name>", "spec": <Spec>} on success
{"error": "<one sentence, user-facing>"} when the request cannot be expressed.
` + AutomationSchema + `
Examples:
- "when the denver-indy round trip on https://flights.example/q/123 drops below 400, email david@email.com" ->
{"name":"Flights DEN-IND under $400","spec":{"condition":{"type":"url_watch","url":"https://flights.example/q/123","question":"What is the cheapest round-trip flight price shown, in USD?","op":"lt","threshold":400},"action":{"type":"email","channelId":"","to":"david@email.com","title":"Flight deal: DEN-IND under $400","body":"A round-trip flight dropped below $400."},"pollMinutes":60,"once":true}}
- "tell me when my inbox gets an invoice" ->
{"name":"Invoice signals","spec":{"condition":{"type":"signal","keyword":"invoice"},"action":{"type":"notify","channelId":""},"pollMinutes":15,"once":false}}
- "book me a hotel" -> {"error":"Superbrain cannot book anything; it can watch a public page and notify you."}`
// Compile turns one natural-language request into a validated task
// proposal. The result is NOT persisted — the user confirms it through the
// regular task-creation endpoint, which validates again.
func Compile(ctx context.Context, text string) (name string, spec Spec, err error) {
// proposal, using the AI config resolved for this user (BYO key first,
// then the server key when the plan allows). The result is NOT persisted —
// the user confirms it through the regular task-creation endpoint, which
// validates again.
func Compile(ctx context.Context, d *db.DB, userID, text string) (name string, spec Spec, err error) {
text = strings.TrimSpace(text)
if text == "" {
return "", Spec{}, errors.New("empty request")
@@ -83,7 +92,11 @@ func Compile(ctx context.Context, text string) (name string, spec Spec, err erro
if len([]rune(text)) > 2000 {
return "", Spec{}, errors.New("request too long (max 2000 characters)")
}
reply, err := ai.Complete(ctx, compileSystem, text)
resolved, err := ai.ResolveForUser(ctx, d, userID)
if err != nil {
return "", Spec{}, err
}
reply, err := ai.Complete(ctx, resolved, compileSystem, text)
if err != nil {
return "", Spec{}, err
}