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).
335 lines
10 KiB
Go
335 lines
10 KiB
Go
package handlers
|
|
|
|
// "Hey Superbrain" automations (internal/agent): compile natural language
|
|
// into a validated task proposal, then owner-confirmed CRUD. The compile
|
|
// step never writes; task creation re-validates the spec server-side —
|
|
// the model is a convenience, ValidateSpec is the boundary.
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"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/db"
|
|
)
|
|
|
|
// compileLimiter bounds NL compilations per user (each one is an LLM call).
|
|
var compileLimiter = auth.NewLimiterStore()
|
|
|
|
// CompileLimiter rate-limits compile requests per effective client IP.
|
|
func CompileLimiter(next http.HandlerFunc) http.HandlerFunc {
|
|
return auth.Limiter(compileLimiter, 10, time.Minute)(next)
|
|
}
|
|
|
|
func sqlNullTime(t time.Time) sql.NullTime { return sql.NullTime{Time: t, Valid: true} }
|
|
|
|
// HandleAgentCompile turns one sentence into a task proposal.
|
|
//
|
|
// POST /api/agent/compile {text}
|
|
// 200 {name, spec, summary} — proposal only; nothing is stored
|
|
// 422 {error} — the model refused or the spec failed validation
|
|
// 503 — AI is not configured on this server
|
|
func HandleAgentCompile(w http.ResponseWriter, r *http.Request) {
|
|
b, ok := read(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
text := strings.TrimSpace(str(b, "text"))
|
|
if text == "" {
|
|
respond(w, 0, nil, bad("text is required"))
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second)
|
|
defer cancel()
|
|
name, spec, err := agent.Compile(ctx, database(r), user(r), text)
|
|
if err != nil {
|
|
var rejected *agent.ErrCompileRejected
|
|
if errors.As(err, &rejected) {
|
|
respond(w, 422, Error{Error: rejected.Reason}, nil)
|
|
return
|
|
}
|
|
if errors.Is(err, 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, 502, Error{Error: "The AI provider could not be reached"}, nil)
|
|
return
|
|
}
|
|
respond(w, 200, object{"name": name, "spec": spec, "summary": agent.Summary(spec)}, nil)
|
|
}
|
|
|
|
func agentTaskProjection(row object) object {
|
|
var spec agent.Spec
|
|
if raw, ok := row["spec"].(string); ok && raw != "" {
|
|
_ = json.Unmarshal([]byte(raw), &spec)
|
|
} else if m, ok := row["spec"].(map[string]any); ok {
|
|
raw, _ := json.Marshal(m)
|
|
_ = json.Unmarshal(raw, &spec)
|
|
}
|
|
return object{
|
|
"id": row["id"], "name": row["name"], "spec": spec,
|
|
"summary": agent.Summary(spec),
|
|
"enabled": row["enabled"], "status": row["status"],
|
|
"fireCount": row["fireCount"], "lastCheckedAt": row["lastCheckedAt"],
|
|
"lastFiredAt": row["lastFiredAt"], "version": row["version"],
|
|
"createdAt": row["createdAt"],
|
|
}
|
|
}
|
|
|
|
// tenantAITaskLimits resolves the caller's plan cap on stored automations.
|
|
func tenantAITaskLimits(r *http.Request) (int64, error) {
|
|
var tenantID *string
|
|
if e := database(r).QueryRowContext(r.Context(),
|
|
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
|
|
return 0, e
|
|
}
|
|
tid := ""
|
|
if tenantID != nil {
|
|
tid = *tenantID
|
|
}
|
|
lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid)
|
|
return lim.AITasks, e
|
|
}
|
|
|
|
func HandleAgentTasksList(w http.ResponseWriter, r *http.Request) {
|
|
rows, e := db.Many(r.Context(), database(r),
|
|
`SELECT to_jsonb(t) FROM "AgentTask" t WHERE "ownerId"=$1 ORDER BY "createdAt" DESC`, user(r))
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
out := []object{}
|
|
for _, row := range rows {
|
|
out = append(out, agentTaskProjection(row))
|
|
}
|
|
respond(w, 200, out, nil)
|
|
}
|
|
|
|
func HandleAgentTasksCreate(w http.ResponseWriter, r *http.Request) {
|
|
b, ok := read(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
name := strings.TrimSpace(str(b, "name"))
|
|
if name == "" || len([]rune(name)) > 120 {
|
|
respond(w, 0, nil, bad("name is required (max 120 characters)"))
|
|
return
|
|
}
|
|
// Plan cap on stored automations (entitlement catalog, not TIER).
|
|
planCap, e := tenantAITaskLimits(r)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
if planCap >= 0 {
|
|
var active int
|
|
if e := database(r).QueryRowContext(r.Context(),
|
|
`SELECT count(*) FROM "AgentTask" WHERE "ownerId"=$1 AND status<>'done'`, user(r)).Scan(&active); e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
if int64(active) >= planCap {
|
|
respond(w, 403, Error{Error: "Not available on your plan"}, nil)
|
|
return
|
|
}
|
|
}
|
|
// The spec may arrive from the compile preview or a hand-built client;
|
|
// it is validated exactly like compiled output — no trusted paths.
|
|
rawSpec, e := json.Marshal(b["spec"])
|
|
if e != nil || b["spec"] == nil {
|
|
respond(w, 0, nil, bad("spec is required"))
|
|
return
|
|
}
|
|
var spec agent.Spec
|
|
if e := json.Unmarshal(rawSpec, &spec); e != nil {
|
|
respond(w, 0, nil, bad("spec is malformed"))
|
|
return
|
|
}
|
|
if e := agent.ValidateSpec(&spec); e != nil {
|
|
respond(w, 0, nil, bad(e.Error()))
|
|
return
|
|
}
|
|
if spec.Action.Type == "notify" && spec.Action.ChannelID != "" {
|
|
// The channel must belong to the caller (compiled specs leave it
|
|
// empty; the UI fills in a chosen owned channel).
|
|
if _, e := owned(r, database(r), "NotificationChannel", spec.Action.ChannelID, "ownerId"); e != nil {
|
|
respond(w, 0, nil, bad("Channel not found"))
|
|
return
|
|
}
|
|
}
|
|
if spec.Action.Type == "notify" && spec.Action.ChannelID == "" {
|
|
respond(w, 0, nil, bad("action.channelId is required for notify"))
|
|
return
|
|
}
|
|
clean, _ := json.Marshal(spec) // re-marshal the NORMALIZED spec
|
|
row, e := db.Insert(r.Context(), database(r), "AgentTask", object{
|
|
"id": db.NewID(), "ownerId": user(r), "name": name, "spec": string(clean),
|
|
})
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
respond(w, 201, agentTaskProjection(row), nil)
|
|
}
|
|
|
|
func HandleAgentTasksUpdate(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
existing, e := owned(r, database(r), "AgentTask", id, "ownerId")
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
b, ok := read(w, r)
|
|
if !ok {
|
|
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("Task was modified elsewhere; reload to see the latest version"))
|
|
return
|
|
}
|
|
updates := object{}
|
|
if _, present := b["name"]; present {
|
|
s := strings.TrimSpace(str(b, "name"))
|
|
if s == "" || len([]rune(s)) > 120 {
|
|
respond(w, 0, nil, bad("name must be 1-120 characters"))
|
|
return
|
|
}
|
|
updates["name"] = s
|
|
}
|
|
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
|
|
// Re-enabling a completed one-shot starts it over.
|
|
if ev {
|
|
updates["status"] = "active"
|
|
}
|
|
}
|
|
if _, present := b["spec"]; present {
|
|
rawSpec, e := json.Marshal(b["spec"])
|
|
if e != nil {
|
|
respond(w, 0, nil, bad("spec is malformed"))
|
|
return
|
|
}
|
|
var spec agent.Spec
|
|
if e := json.Unmarshal(rawSpec, &spec); e != nil {
|
|
respond(w, 0, nil, bad("spec is malformed"))
|
|
return
|
|
}
|
|
if e := agent.ValidateSpec(&spec); e != nil {
|
|
respond(w, 0, nil, bad(e.Error()))
|
|
return
|
|
}
|
|
if spec.Action.Type == "notify" {
|
|
if spec.Action.ChannelID == "" {
|
|
respond(w, 0, nil, bad("action.channelId is required for notify"))
|
|
return
|
|
}
|
|
if _, e := owned(r, database(r), "NotificationChannel", spec.Action.ChannelID, "ownerId"); e != nil {
|
|
respond(w, 0, nil, bad("Channel not found"))
|
|
return
|
|
}
|
|
}
|
|
clean, _ := json.Marshal(spec)
|
|
updates["spec"] = string(clean)
|
|
}
|
|
if len(updates) == 0 {
|
|
respond(w, 0, nil, bad("Nothing to update"))
|
|
return
|
|
}
|
|
row, e := patchVersioned(r, "AgentTask", id, baseVersion, updates)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
respond(w, 200, agentTaskProjection(row), nil)
|
|
}
|
|
|
|
func HandleAgentTasksDelete(w http.ResponseWriter, r *http.Request) {
|
|
respond(w, 200, object{"ok": true}, remove(r, "AgentTask", r.PathValue("id"), "ownerId"))
|
|
}
|
|
|
|
// HandleAgentTasksRun evaluates one task immediately (the UI's "Run now").
|
|
// It respects every engine cap; only the schedule check is bypassed.
|
|
func HandleAgentTasksRun(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
row, e := owned(r, database(r), "AgentTask", id, "ownerId")
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
rawSpec, _ := json.Marshal(row["spec"])
|
|
var spec agent.Spec
|
|
if e := json.Unmarshal(rawSpec, &spec); e != nil {
|
|
respond(w, 0, nil, bad("Stored spec is unreadable"))
|
|
return
|
|
}
|
|
if e := agent.ValidateSpec(&spec); e != nil {
|
|
respond(w, 0, nil, bad("Stored spec is no longer valid: "+e.Error()))
|
|
return
|
|
}
|
|
var fireCount int
|
|
if v, ok := row["fireCount"].(float64); ok {
|
|
fireCount = int(v)
|
|
}
|
|
t := agent.Task{
|
|
ID: id, OwnerID: user(r), Name: str(row, "name"), Spec: spec,
|
|
Status: str(row, "status"), FireCount: fireCount,
|
|
}
|
|
if v, ok := row["lastCheckedAt"].(string); ok && v != "" {
|
|
if ts, e := time.Parse(time.RFC3339, v); e == nil {
|
|
t.LastChecked = sqlNullTime(ts)
|
|
}
|
|
}
|
|
// CreatedAt floors the signal scan on a never-checked task; without it a
|
|
// first manual run would match the owner's entire signal history.
|
|
if v, ok := row["createdAt"].(string); ok && v != "" {
|
|
if ts, e := time.Parse(time.RFC3339, v); e == nil {
|
|
t.CreatedAt = ts
|
|
}
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
|
defer cancel()
|
|
outcome := agent.RunTask(ctx, database(r), t)
|
|
respond(w, 200, object{"outcome": outcome}, nil)
|
|
}
|
|
|
|
func HandleAgentRunsList(w http.ResponseWriter, r *http.Request) {
|
|
taskID := strings.TrimSpace(r.URL.Query().Get("taskId"))
|
|
q := `SELECT to_jsonb(r) FROM "AgentRun" r WHERE r."ownerId"=$1`
|
|
args := []any{user(r)}
|
|
if taskID != "" {
|
|
q += ` AND r."taskId"=$2`
|
|
args = append(args, taskID)
|
|
}
|
|
q += ` ORDER BY r."createdAt" DESC LIMIT 50`
|
|
rows, e := db.Many(r.Context(), database(r), q, args...)
|
|
if e != nil {
|
|
respond(w, 0, nil, e)
|
|
return
|
|
}
|
|
out := []object{}
|
|
for _, row := range rows {
|
|
out = append(out, object{
|
|
"id": row["id"], "taskId": row["taskId"], "outcome": row["outcome"],
|
|
"detail": row["detail"], "createdAt": row["createdAt"],
|
|
})
|
|
}
|
|
respond(w, 200, out, nil)
|
|
}
|