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) }