Add agent automations: 'hey superbrain' NL-compiled watch-and-act tasks
release gate / check (push) Failing after 6m37s
release gate / check (push) Failing after 6m37s
The first real-agent slice (PLAN_PRICING_TIERS step 5, partial): describe
an automation in plain language — 'when the round trip on <url> drops
below $400, email david@…' — and Superbrain compiles it into a task the
user reviews and confirms before anything is stored.
Trust model (the point of the whole design): the LLM only ever PROPOSES.
Compile output and hand-built specs pass the same server-side
agent.ValidateSpec on every write AND on every engine load (a spec that
stops validating is paused, never executed). Actions are a closed set —
notify an owned channel, email one recipient, save one bookmark — with no
destructive or cross-user capability. Fetched page content is untrusted:
delimited in the extraction prompt, schema-checked reply ({found,value,
text,summary}), and no action can be chosen or retargeted by page text.
Multi-step requests (flights AND hotels bundled) are explicitly refused by
the compiler until chaining exists.
internal/ai: OpenAI-compatible gateway (OpenRouter default via AI_API_KEY/
AI_MODEL/AI_BASE_URL; any compatible endpoint works — house Core gateway or
Ollama later). Netguard-dialed, outbound-budgeted, balanced-brace JSON
extraction, provider bodies never echoed wholesale (they can reflect keys).
internal/agent: url_watch (scheduled fetch + one extracted fact + numeric/
text comparison) and signal (new mailbox signals, keyword filter)
conditions; poll floor 15min, once-semantics, per-task email cap 5,
per-owner daily email cap 20, global advisory tick lease, bounded run
history (pruned tail + age horizon). Engine loop joins signals/notify in
main's shutdown contract.
Schema: AgentTask + AgentRun (migration 014, converge-verified).
Entitlements: AITasks cap per plan (free 2 / standard 10 / premium 50 /
core+selfhosted unlimited) + ai_tasks override key — stored-task count is
plan data, never TIER checks.
API: /api/agent/compile (rate-limited, 422 surfaces the model's refusal,
503 when AI unconfigured), task CRUD with the version contract, manual
/run, bounded /runs history. Web: Settings -> Automations with the
composer, human-readable proposal + raw-spec review, channel picker for
notify actions, task list with Run now, and the runs strip (SafeTime for
hydration-safe timestamps).
Tests: loopback fake OpenAI-compatible server + watch target + the SMTP
fake — compile success/refusal/invalid-spec, create-time validation
(javascript: URLs rejected), version contract, url_watch fire with
once-completion, signal fire + no-refire without new signals, plan cap via
ai_tasks override, 503 without a key. Full suite green (-race); converge
green; web lint/SSR-eslint/build clean.
Docs: API.md agent section, RUNNING.md, .env.example (key stays in .env
only), compose passthrough.
This commit is contained in:
@@ -0,0 +1,338 @@
|
||||
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
|
||||
}
|
||||
if !ai.Configured() {
|
||||
respond(w, 503, Error{Error: "AI is not configured on this server"}, nil)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second)
|
||||
defer cancel()
|
||||
name, spec, err := agent.Compile(ctx, 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.ErrNotConfigured) {
|
||||
respond(w, 503, Error{Error: "AI is not configured on this server"}, 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)
|
||||
}
|
||||
Reference in New Issue
Block a user