Promotes Automations to a top-level sidebar group (below Bookmarks) with user-defined AgentGroup folders (migration 025, FK SET NULL on delete). The /automations page becomes master-detail: overview (composer + grouped list + named global runs) and per-task detail (original prompt, group assignment, run-now/pause/delete, per-task run timeline with true/false/ error pills). Editing recompiles through /api/agent/compile and confirms the proposal before a versioned PATCH applies spec+prompt — the model never writes. Tasks store prompt+groupId; projections add runCount/ errorCount; runs carry taskName. The engine is untouched: groups/prompt are metadata, the validated spec remains the only thing it executes. Chaining, refinements and dry-run stay phase 2. Verified: full DB integration suite under -race, db-converge + migration atomicity, web lint/SSR/build, and a rewritten browser regression covering the sidebar folder, detail prompt, per-task runs, recompile-to-edit and named global runs.
469 lines
14 KiB
Go
469 lines
14 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"
|
|
|
|
"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"],
|
|
"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"],
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
row, e := db.Insert(r.Context(), database(r), "AgentTask", object{
|
|
"id": db.NewID(), "ownerId": user(r), "name": name, "spec": string(clean),
|
|
"prompt": prompt, "groupId": groupID,
|
|
})
|
|
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 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"))
|
|
}
|