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).
135 lines
5.8 KiB
Go
135 lines
5.8 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/andrew/superbrain/internal/ai"
|
|
"github.com/andrew/superbrain/internal/db"
|
|
)
|
|
|
|
// ErrCompileRejected means the model could not (or refused to) express the
|
|
// request as a task. The message is safe to show the user verbatim.
|
|
type ErrCompileRejected struct{ Reason string }
|
|
|
|
func (e *ErrCompileRejected) Error() string { return "compile rejected: " + e.Reason }
|
|
|
|
// 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",
|
|
"url": absolute http(s) URL to poll (url_watch only),
|
|
"question": what to look for on the page, <=500 chars (url_watch only),
|
|
"op": "any" | "lt" | "lte" | "gt" | "gte" | "eq" | "contains",
|
|
"threshold": number for lt/lte/gt/gte,
|
|
"text": string for eq/contains,
|
|
"keyword": optional keyword filter (signal only)
|
|
},
|
|
"action": {
|
|
"type": "notify" | "email" | "bookmark",
|
|
"channelId": existing notification channel id (notify only; you do NOT know ids - put "" and the user picks one),
|
|
"to": recipient email (email only),
|
|
"title": message/bookmark title,
|
|
"body": message body,
|
|
"url": URL to save (bookmark only)
|
|
},
|
|
"pollMinutes": 15..10080 (default 60),
|
|
"once": true for one-shot deals, false for ongoing watches
|
|
}
|
|
|
|
What Superbrain can actually do — anything else MUST be refused:
|
|
- url_watch: fetch a PUBLIC web page on a schedule and answer one question
|
|
about it (prices, availability, a phrase). It cannot log in, search
|
|
engines, book anything, or chain multiple sites. Multi-step requests
|
|
(e.g. "watch flights AND then search hotels") must be refused with an
|
|
explanation that one watch per task is supported today.
|
|
- signal: fire when the user's existing mailbox watchers produce a new
|
|
signal, optionally filtered by keyword.
|
|
- Actions: notify (an existing channel), email (one message to one fixed
|
|
recipient), bookmark (save one URL for the user).
|
|
|
|
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, 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")
|
|
}
|
|
if len([]rune(text)) > 2000 {
|
|
return "", Spec{}, errors.New("request too long (max 2000 characters)")
|
|
}
|
|
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
|
|
}
|
|
raw, err := ai.ExtractJSON(reply)
|
|
if err != nil {
|
|
return "", Spec{}, fmt.Errorf("model reply was not JSON: %w", err)
|
|
}
|
|
var out struct {
|
|
Name string `json:"name"`
|
|
Spec *Spec `json:"spec"`
|
|
Error string `json:"error"`
|
|
}
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
return "", Spec{}, fmt.Errorf("model reply did not match the compiler schema: %w", err)
|
|
}
|
|
if out.Error != "" {
|
|
return "", Spec{}, &ErrCompileRejected{Reason: out.Error}
|
|
}
|
|
if out.Spec == nil {
|
|
return "", Spec{}, &ErrCompileRejected{Reason: "the model returned neither a task nor an explanation"}
|
|
}
|
|
name = strings.TrimSpace(out.Name)
|
|
if name == "" {
|
|
name = "Automation"
|
|
}
|
|
if len([]rune(name)) > 120 {
|
|
name = string([]rune(name)[:120])
|
|
}
|
|
// The validator, not the model, decides what a task is.
|
|
if err := ValidateSpec(out.Spec); err != nil {
|
|
return "", Spec{}, &ErrCompileRejected{Reason: "the proposed task failed validation: " + err.Error()}
|
|
}
|
|
// A compiled notify action never knows channel ids; the UI fills it in.
|
|
return name, *out.Spec, nil
|
|
}
|