Files
superbrain/internal/handlers/ai.go
T
Andrew S Erwin 0848453732
release gate / check (push) Failing after 6m21s
Add the Superbrain assistant: ephemeral chat drawer with automation proposals
The A+B slice: one conversation surface for questions AND automations.

Backend: POST /api/ai/chat — ephemeral multi-turn chat through the same
per-user AI resolution as everything else (BYO key -> plan-gated server
key -> 428). The server is stateless per request: the browser owns
history, the handler caps it anyway (40 messages accepted, last 20 used,
8k chars each, last turn must be the user's). Per-user rate limit
(30/hour, keyed on the account not the IP) and a 50-second budget inside
the proxy's 55s window.

The chat system prompt embeds agent.AutomationSchema — the SAME contract
text the compiler uses — so chat proposals and compiled tasks can never
drift. The model answers in a {reply, automation|null} JSON envelope; a
proposal reaches the client only if its spec passes agent.ValidateSpec
(invalid ones are dropped silently, the reply survives), and model-
invented channelIds are scrubbed so the UI always picks from the user's
real channels. A model that ignores the envelope degrades gracefully: raw
text becomes the reply, no proposal.

Web: components/assistant.tsx — floating launcher on every signed-in
screen (mounted once in AppShellWrapper so conversations survive in-app
navigation), Sheet drawer with markdown rendering (house ReactMarkdown +
remarkGfm pattern), proposal cards (channel picker for notify, editable
recipient for email, Create automation -> the regular tasks endpoint),
and Save to page (Markdown transcript into Pages — the only persistence,
by design). Enter sends, Shift+Enter newline.

Tests: envelope parsing, valid proposal + channelId scrub, invalid-spec
drop with reply intact, non-JSON graceful fallback, request validation
(empty/assistant-last/system-role), multi-turn passthrough, 428 path.
Full suite green (-race); web lint/SSR-eslint/build clean.

Docs: API.md chat endpoint, RUNNING.md 'two doors' framing (drawer +
Settings), README feature bullet, plan/notes docs updated.
2026-10-28 19:38:45 -05:00

400 lines
14 KiB
Go

package handlers
// Per-user AI configuration (Settings → AI): provider, model, base URL and
// a bring-your-own API key. Config is data; internal/ai is the
// implementation. The key is encrypted at rest (internal/crypto, the same
// versioned format as every other stored credential), masked in every
// response, and a PUT echoing the mask keeps the stored key. The server
// env key remains the plan-gated fallback (entitlements.AllowServerAI).
import (
"context"
"database/sql"
"encoding/json"
"errors"
"net/http"
"net/url"
"strings"
"time"
"github.com/andrew/superbrain/internal/agent"
"github.com/andrew/superbrain/internal/ai"
"github.com/andrew/superbrain/internal/auth"
"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"
)
// aiKeyMask mirrors the notification-channel mask: write-only secrets.
const aiKeyMask = "••••••••"
// defaultBaseURLs per provider (empty user input falls back to these).
var aiDefaultBaseURLs = map[string]string{
ai.ProviderOpenAICompatible: "https://openrouter.ai/api/v1",
ai.ProviderAnthropic: "https://api.anthropic.com",
ai.ProviderGemini: "https://generativelanguage.googleapis.com",
}
func aiConfigProjection(row object) object {
masked := ""
if s, _ := row["apiKey"].(string); s != "" {
masked = aiKeyMask
}
return object{
"id": row["id"], "provider": row["provider"], "baseUrl": row["baseUrl"],
"model": row["model"], "apiKey": masked, "enabled": row["enabled"],
"version": row["version"], "createdAt": row["createdAt"],
}
}
// HandleAiConfigGet returns the caller's stored config (masked) or null.
func HandleAiConfigGet(w http.ResponseWriter, r *http.Request) {
row, e := db.One(r.Context(), database(r),
`SELECT to_jsonb(t) FROM "UserAiConfig" t WHERE "ownerId"=$1`, user(r))
if errors.Is(e, db.ErrNotFound) {
respond(w, 200, nil, nil)
return
}
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, aiConfigProjection(row), nil)
}
// HandleAiConfigPut creates or updates the caller's config (upsert; one row
// per user). The version contract applies when a row exists.
func HandleAiConfigPut(w http.ResponseWriter, r *http.Request) {
b, ok := read(w, r)
if !ok {
return
}
provider := strings.TrimSpace(str(b, "provider"))
if !ai.ValidProvider(provider) {
respond(w, 0, nil, bad("provider must be openai-compatible, anthropic or gemini"))
return
}
model := strings.TrimSpace(str(b, "model"))
if model == "" || len([]rune(model)) > 200 {
respond(w, 0, nil, bad("model is required (max 200 characters)"))
return
}
baseURL := strings.TrimSpace(str(b, "baseUrl"))
if baseURL == "" {
baseURL = aiDefaultBaseURLs[provider]
}
if u, e := url.Parse(baseURL); e != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
respond(w, 0, nil, bad("baseUrl must be an absolute http(s) URL"))
return
}
submittedKey := str(b, "apiKey")
existing, e := db.One(r.Context(), database(r),
`SELECT to_jsonb(t) FROM "UserAiConfig" t WHERE "ownerId"=$1`, user(r))
notFound := errors.Is(e, db.ErrNotFound)
if e != nil && !notFound {
respond(w, 0, nil, e)
return
}
// Resolve the effective key: a mask (or empty on update) keeps the
// stored one; anything else is a new plaintext key.
var encKey string
if notFound {
if submittedKey == "" || submittedKey == aiKeyMask {
respond(w, 0, nil, bad("apiKey is required"))
return
}
if len(submittedKey) > 500 {
respond(w, 0, nil, bad("apiKey is too long"))
return
}
encKey, e = crypt.Encrypt(submittedKey, config.Load().EncryptionSecret())
if e != nil {
respond(w, 0, nil, e)
return
}
enabled := true
if v, ok := b["enabled"].(bool); ok {
enabled = v
}
row, e := db.Insert(r.Context(), database(r), "UserAiConfig", object{
"id": db.NewID(), "ownerId": user(r), "provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"), "model": model,
"apiKey": encKey, "enabled": enabled,
})
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 201, aiConfigProjection(row), nil)
return
}
baseVersion, e := requiredVersion(b)
if e != nil {
respond(w, 0, nil, e)
return
}
if stored, _ := existing["version"].(float64); int(stored) != baseVersion {
respond(w, 0, nil, conflict("AI config was modified elsewhere; reload to see the latest version"))
return
}
if submittedKey != "" && submittedKey != aiKeyMask {
if len(submittedKey) > 500 {
respond(w, 0, nil, bad("apiKey is too long"))
return
}
encKey, e = crypt.Encrypt(submittedKey, config.Load().EncryptionSecret())
if e != nil {
respond(w, 0, nil, e)
return
}
}
updates := object{
"provider": provider,
"baseUrl": strings.TrimRight(baseURL, "/"),
"model": model,
}
if encKey != "" {
updates["apiKey"] = encKey
}
if v, present := b["enabled"]; present {
ev, ok := v.(bool)
if !ok {
respond(w, 0, nil, bad("enabled must be boolean"))
return
}
updates["enabled"] = ev
}
id, _ := existing["id"].(string)
row, e := patchVersioned(r, "UserAiConfig", id, baseVersion, updates)
if e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, aiConfigProjection(row), nil)
}
// HandleAiConfigDelete removes the caller's BYO config (falls back to the
// server key when the plan allows it).
func HandleAiConfigDelete(w http.ResponseWriter, r *http.Request) {
res, e := database(r).ExecContext(r.Context(),
`DELETE FROM "UserAiConfig" WHERE "ownerId"=$1`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
if n, _ := res.RowsAffected(); n == 0 {
respond(w, 0, nil, db.ErrNotFound)
return
}
respond(w, 200, object{"ok": true}, nil)
}
// HandleAiTest sends a one-token completion through the CALLER's resolved
// config (BYO first, then plan-gated server key) so misconfiguration fails
// here, not inside a scheduled task.
func HandleAiTest(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
resolved, e := ai.ResolveForUser(ctx, database(r), user(r))
if e != nil {
if errors.Is(e, ai.ErrNoAI) {
respond(w, 428, Error{Error: "No AI configuration available: save your own key, or the server key is not included in your plan."}, nil)
return
}
respond(w, 0, nil, e)
return
}
reply, e := ai.Complete(ctx, resolved,
"You are a connectivity probe. Reply with exactly one word: pong", "ping")
if e != nil {
respond(w, 502, Error{Error: "AI test failed: " + truncate(e.Error(), 200)}, nil)
return
}
respond(w, 200, object{"ok": true, "source": resolved.Source, "model": resolved.Model, "reply": truncate(strings.TrimSpace(reply), 100)}, nil)
}
// HandleAiStatus reports what the UI needs to explain availability:
// whether the user has a BYO config, whether a server key exists AND the
// plan may use it, and which source is effective. No secrets, ever.
func HandleAiStatus(w http.ResponseWriter, r *http.Request) {
var configured, enabled bool
e := database(r).QueryRowContext(r.Context(),
`SELECT enabled FROM "UserAiConfig" WHERE "ownerId"=$1`, user(r)).Scan(&enabled)
if e != nil && !errors.Is(e, sql.ErrNoRows) {
respond(w, 0, nil, e)
return
}
configured = e == nil
var tenantID *string
if e := database(r).QueryRowContext(r.Context(),
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
respond(w, 0, nil, e)
return
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
plan, e := db.NewTenantRepo(database(r)).Plan(r.Context(), tid)
if e != nil {
respond(w, 0, nil, e)
return
}
serverSet := ai.ServerConfigured()
serverAllowed := serverSet && entitlements.AllowServerAI(plan)
effective := "none"
if configured && enabled {
effective = "user"
} else if serverAllowed {
effective = "server"
}
respond(w, 200, object{
"userConfigured": configured,
"userEnabled": configured && enabled,
"serverAvailable": serverAllowed, // deliberately conflated: whether a
// server key EXISTS is an operator secret-free fact, but whether
// this user may use it is the only thing the UI should act on.
"effective": effective,
"plan": string(plan),
}, nil)
}
// --- Assistant chat (ephemeral, proposal-capable) ---------------------------
// chatLimiter bounds chat turns per USER (not per IP: one NAT could
// otherwise starve a household, and the cost center is the account).
var chatLimiter = auth.NewLimiterStore()
// ChatLimiter rate-limits chat messages per authenticated user.
func ChatLimiter(next http.HandlerFunc) http.HandlerFunc {
return auth.LimiterKeyed(chatLimiter, 30, time.Hour, user)(next)
}
// chatSystem is the assistant persona. It shares the automation contract
// with the compiler (agent.AutomationSchema) so chat proposals and compiled
// tasks can never drift. The envelope is JSON so proposals are separable
// from prose; a model that answers in plain text anyway is handled
// gracefully (the text becomes the reply, no proposal).
const chatSystem = `You are Superbrain's in-app assistant: concise, practical, warm but not gushy. Answer in GitHub-flavored markdown.
You help with: general questions; drafting, summarizing and rewriting text; explaining Superbrain features (bookmarks with previews/tags/due dates, Markdown pages with backlinks, collections with typed properties and saved views, kanban boards, shared calendar dates, contacts, mailbox signals, notification rules, automations); and proposing automations.
You have NO access to the user's data and CANNOT perform actions — never claim to have looked anything up, saved anything, or sent anything. When the user wants something done in their workspace, explain where the feature lives, or propose an automation.
AUTOMATIONS: when — and only when — the user asks to watch/monitor/be told about something that fits the schema below, include an "automation" object; otherwise "automation": null. The same hard limits as the compiler apply: one condition, one action, no logins, no purchases, no invented URLs, no multi-step chains — refuse those in your reply text with automation null.
` + agent.AutomationSchema + `
REPLY FORMAT — always ONE JSON object, no prose outside it:
{"reply": "<your markdown answer>", "automation": {"name": "...", "spec": <Spec>} or null}`
// HandleAiChat is the assistant endpoint: ephemeral multi-turn chat with
// optional automation proposals. The browser keeps the history; the server
// is stateless per request (bounded message count/size, oldest turns
// dropped server-side too so a hand-rolled client cannot smuggle a novel).
//
// POST /api/ai/chat {messages:[{role,content},...]}
// 200 {reply, proposal?} proposal = {name, spec, summary} when the
// model suggested a VALID automation
// 428 no AI available for this user
func HandleAiChat(w http.ResponseWriter, r *http.Request) {
b, ok := read(w, r)
if !ok {
return
}
rawMsgs, _ := b["messages"].([]any)
if len(rawMsgs) == 0 {
respond(w, 0, nil, bad("messages is required"))
return
}
if len(rawMsgs) > 40 {
respond(w, 0, nil, bad("conversation too long (max 40 messages)"))
return
}
msgs := make([]ai.Message, 0, len(rawMsgs))
for _, m := range rawMsgs {
mm, _ := m.(map[string]any)
role, _ := mm["role"].(string)
content, _ := mm["content"].(string)
if role != "user" && role != "assistant" {
respond(w, 0, nil, bad("message roles must be user or assistant"))
return
}
content = strings.TrimSpace(content)
if content == "" || len([]rune(content)) > 8000 {
respond(w, 0, nil, bad("messages must be 1-8000 characters"))
return
}
msgs = append(msgs, ai.Message{Role: role, Content: content})
}
// The last turn must be the user's; the assistant never answers itself.
if msgs[len(msgs)-1].Role != "user" {
respond(w, 0, nil, bad("the last message must be from the user"))
return
}
// Keep only the most recent window regardless of what the client sent.
if len(msgs) > 20 {
msgs = msgs[len(msgs)-20:]
}
// 50s: inside the web proxy's 55s budget and Go's 60s WriteTimeout.
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
defer cancel()
resolved, e := ai.ResolveForUser(ctx, database(r), user(r))
if e != nil {
if errors.Is(e, ai.ErrNoAI) {
respond(w, 428, Error{Error: "AI is not configured. Add your own provider and API key in Settings → AI."}, nil)
return
}
respond(w, 0, nil, e)
return
}
reply, e := ai.CompleteMessages(ctx, resolved, chatSystem, msgs)
if e != nil {
respond(w, 502, Error{Error: "The AI provider could not be reached"}, nil)
return
}
// Parse the envelope. Graceful degradation: a model that ignored the
// JSON contract still produces a usable chat reply — the raw text
// becomes the message and no proposal is offered.
out := object{"reply": strings.TrimSpace(reply)}
if raw, jerr := ai.ExtractJSON(reply); jerr == nil {
var env struct {
Reply string `json:"reply"`
Automation *struct {
Name string `json:"name"`
Spec agent.Spec `json:"spec"`
} `json:"automation"`
}
if json.Unmarshal(raw, &env) == nil && strings.TrimSpace(env.Reply) != "" {
out["reply"] = strings.TrimSpace(env.Reply)
if env.Automation != nil {
spec := env.Automation.Spec
// The validator, not the model, decides what a proposal is.
if verr := agent.ValidateSpec(&spec); verr == nil {
name := strings.TrimSpace(env.Automation.Name)
if name == "" {
name = "Automation"
}
if len([]rune(name)) > 120 {
name = string([]rune(name)[:120])
}
// Never echo a model-invented channel id: the UI picks
// from the user's real channels.
if spec.Action.Type == "notify" {
spec.Action.ChannelID = ""
}
out["proposal"] = object{"name": name, "spec": spec, "summary": agent.Summary(spec)}
}
}
}
}
respond(w, 200, out, nil)
}