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" "gitea.federated.computer/Federated_Computer/superbrain/internal/agent" "gitea.federated.computer/Federated_Computer/superbrain/internal/ai" "gitea.federated.computer/Federated_Computer/superbrain/internal/auth" "gitea.federated.computer/Federated_Computer/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), "prompt": row["prompt"], "groupId": row["groupId"], "refinements": normalizeRefinements(row["refinements"]), "calls": spec.Calls, "calledOnly": spec.CalledOnly, "runCount": row["runCount"], "errorCount": row["errorCount"], "enabled": row["enabled"], "status": row["status"], "fireCount": row["fireCount"], "lastCheckedAt": row["lastCheckedAt"], "lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"], } } // normalizeRefinements coerces the stored jsonb (array, or its text form) // into a []string for the projection. func normalizeRefinements(v any) []string { switch x := v.(type) { case []any: out := []string{} for _, e := range x { if s, ok := e.(string); ok { out = append(out, s) } } return out case string: var out []string _ = json.Unmarshal([]byte(x), &out) if out == nil { out = []string{} } return out } return []string{} } // cleanRefinements validates the submitted refinements list (ordered added // constraints; the UI composes prompt+refinements into the compile text). func cleanRefinements(v any) ([]string, error) { if v == nil { return []string{}, nil } arr, ok := v.([]any) if !ok { return nil, bad("refinements must be an array of strings") } if len(arr) > 20 { return nil, bad("at most 20 refinements") } out := []string{} for _, e := range arr { s, ok := e.(string) if !ok { return nil, bad("refinements must be an array of strings") } s = strings.TrimSpace(s) if s == "" { continue } if len([]rune(s)) > 500 { return nil, bad("each refinement must be at most 500 characters") } out = append(out, s) } return out, nil } // validateAgentCalls checks the callee list: same-owner existing tasks, no // self-call, and no cycle in the owner's call graph (with selfID's calls // overridden by the proposed list). selfID is the task being written (a // fresh id for create). The engine adds a runtime visited-set + depth cap. func validateAgentCalls(r *http.Request, selfID string, calls []string) error { if len(calls) == 0 { return nil } for _, cid := range calls { if cid == selfID { return bad("an automation cannot call itself") } if _, e := owned(r, database(r), "AgentTask", cid, "ownerId"); e != nil { return bad("Called automation not found") } } rows, e := db.Many(r.Context(), database(r), `SELECT to_jsonb(x) FROM (SELECT id, COALESCE(spec->'calls','[]'::jsonb)::text AS calls FROM "AgentTask" WHERE "ownerId"=$1) x`, user(r)) if e != nil { return e } graph := map[string][]string{} for _, row := range rows { var cs []string _ = json.Unmarshal([]byte(str(row, "calls")), &cs) graph[str(row, "id")] = cs } graph[selfID] = calls // DFS from selfID: a cycle exists iff selfID is reachable from itself. visited := map[string]bool{} var dfs func(string) bool dfs = func(n string) bool { for _, m := range graph[n] { if m == selfID { return true } if visited[m] { continue } visited[m] = true if dfs(m) { return true } } return false } if dfs(selfID) { return bad("that call would create a loop") } return nil } // agentGroupRef validates an optional groupId against the caller's own // groups; "" / null clears it (ungrouped). func agentGroupRef(r *http.Request, v any) (any, error) { if v == nil { return nil, nil } s, ok := v.(string) if !ok { return nil, bad("groupId must be a string or null") } s = strings.TrimSpace(s) if s == "" { return nil, nil } if _, e := owned(r, database(r), "AgentGroup", s, "ownerId"); e != nil { return nil, bad("Group not found") } return s, nil } // 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)||jsonb_build_object( 'runCount',(SELECT count(*) FROM "AgentRun" r WHERE r."taskId"=t.id), 'errorCount',(SELECT count(*) FROM "AgentRun" r WHERE r."taskId"=t.id AND r.outcome='failed')) 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 prompt := strings.TrimSpace(str(b, "prompt")) if len([]rune(prompt)) > 4000 { respond(w, 0, nil, bad("prompt must be at most 4000 characters")) return } groupID, e := agentGroupRef(r, b["groupId"]) if e != nil { respond(w, 0, nil, e) return } refs, e := cleanRefinements(b["refinements"]) if e != nil { respond(w, 0, nil, e) return } id := db.NewID() if e := validateAgentCalls(r, id, spec.Calls); e != nil { respond(w, 0, nil, e) return } refsJSON, _ := json.Marshal(refs) row, e := db.Insert(r.Context(), database(r), "AgentTask", object{ "id": id, "ownerId": user(r), "name": name, "spec": string(clean), "prompt": prompt, "groupId": groupID, "refinements": string(refsJSON), }) 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["prompt"]; present { s := strings.TrimSpace(str(b, "prompt")) if len([]rune(s)) > 4000 { respond(w, 0, nil, bad("prompt must be at most 4000 characters")) return } updates["prompt"] = s } if _, present := b["groupId"]; present { g, e := agentGroupRef(r, b["groupId"]) if e != nil { respond(w, 0, nil, e) return } updates["groupId"] = g } 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 e := validateAgentCalls(r, id, spec.Calls); e != nil { respond(w, 0, nil, e) return } } if _, present := b["refinements"]; present { refs, e := cleanRefinements(b["refinements"]) if e != nil { respond(w, 0, nil, e) return } rj, _ := json.Marshal(refs) updates["refinements"] = string(rj) } 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)||jsonb_build_object('taskName',t.name) FROM "AgentRun" r JOIN "AgentTask" t ON t.id=r."taskId" 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"], "taskName": row["taskName"], "outcome": row["outcome"], "detail": row["detail"], "createdAt": row["createdAt"], }) } respond(w, 200, out, nil) } // --- Automation groups (workspace phase 1) --------------------------------- // User-defined folders for the sidebar and the workspace. Deleting a group // ungroups its tasks (FK SET NULL); it never deletes automations. The // engine never reads groups. func HandleAgentGroupsList(w http.ResponseWriter, r *http.Request) { rows, e := db.Many(r.Context(), database(r), `SELECT to_jsonb(g) FROM "AgentGroup" g WHERE "ownerId"=$1 ORDER BY g.position, g."createdAt"`, user(r)) if e != nil { respond(w, 0, nil, e) return } out := []object{} for _, row := range rows { out = append(out, object{ "id": row["id"], "name": row["name"], "position": row["position"], "version": row["version"], "createdAt": row["createdAt"], }) } respond(w, 200, out, nil) } func HandleAgentGroupsCreate(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)) > 80 { respond(w, 0, nil, bad("name is required (max 80 characters)")) return } var pos int if e := database(r).QueryRowContext(r.Context(), `SELECT COALESCE(max(position),-1)+1 FROM "AgentGroup" WHERE "ownerId"=$1`, user(r)).Scan(&pos); e != nil { respond(w, 0, nil, e) return } row, e := db.Insert(r.Context(), database(r), "AgentGroup", object{ "id": db.NewID(), "ownerId": user(r), "name": name, "position": pos, }) if e != nil { respond(w, 0, nil, e) return } respond(w, 201, object{"id": row["id"], "name": row["name"], "position": row["position"], "version": row["version"]}, nil) } func HandleAgentGroupsUpdate(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if _, e := owned(r, database(r), "AgentGroup", id, "ownerId"); 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 } name := strings.TrimSpace(str(b, "name")) if name == "" || len([]rune(name)) > 80 { respond(w, 0, nil, bad("name is required (max 80 characters)")) return } row, e := patchVersioned(r, "AgentGroup", id, baseVersion, object{"name": name}) if e != nil { respond(w, 0, nil, e) return } respond(w, 200, object{"id": row["id"], "name": row["name"], "position": row["position"], "version": row["version"]}, nil) } func HandleAgentGroupsDelete(w http.ResponseWriter, r *http.Request) { respond(w, 200, object{"ok": true}, remove(r, "AgentGroup", r.PathValue("id"), "ownerId")) } // --- Dry run ("Try it") ---------------------------------------------------- // Evaluates a spec's condition WITHOUT firing actions, calling callees, or // recording a run. Accepts an inline spec so the UI can preview a proposed // (not-yet-stored) refinement. Uses the AI/fetch budgets like a real check. var dryRunLimiter = auth.NewLimiterStore() func DryRunLimiter(next http.HandlerFunc) http.HandlerFunc { return auth.Limiter(dryRunLimiter, 20, time.Minute)(next) } func HandleAgentDryRun(w http.ResponseWriter, r *http.Request) { b, ok := read(w, r) if !ok { return } if b["spec"] == nil { respond(w, 0, nil, bad("spec is required")) return } 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 } t := agent.Task{ ID: "dry-run", OwnerID: user(r), Name: strings.TrimSpace(str(b, "name")), Spec: spec, Status: "active", Enabled: true, CreatedAt: time.Now(), } ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) defer cancel() matched, detail := agent.DryRun(ctx, database(r), t) respond(w, 200, object{"matched": matched, "detail": detail}, nil) }