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,171 @@
|
||||
// Package agent implements "hey superbrain" automations: user-confirmed
|
||||
// tasks compiled from natural language, evaluated on a schedule, with
|
||||
// bounded actions (DESIGN record: PLAN_PRICING_TIERS step 5 groundwork).
|
||||
//
|
||||
// Safety model (non-negotiable):
|
||||
// - The LLM COMPILES intent into a spec; the spec is validated by code
|
||||
// and every action executes through fixed, allowlisted primitives.
|
||||
// Model output never becomes an instruction path.
|
||||
// - Fetched web content is untrusted input: it is delimited in the
|
||||
// extraction prompt, the reply is schema-checked, and no action can be
|
||||
// chosen or retargeted by page content.
|
||||
// - Actions are deliberately small: notify an existing channel, send one
|
||||
// email, create one bookmark. No deletes, no sharing changes, no
|
||||
// writes to other users' data, ever.
|
||||
// - Every fetch is netguard-dialed inside an outbound budget; tasks have
|
||||
// poll floors, once-semantics, fire caps and per-owner daily email caps.
|
||||
package agent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Spec is the compiled, validated automation. It is stored verbatim in
|
||||
// AgentTask.spec and is the ONLY thing the engine executes.
|
||||
type Spec struct {
|
||||
Condition Condition `json:"condition"`
|
||||
Action Action `json:"action"`
|
||||
PollMinutes int `json:"pollMinutes"`
|
||||
Once bool `json:"once"`
|
||||
}
|
||||
|
||||
// Condition types:
|
||||
//
|
||||
// url_watch — periodically fetch a public URL and answer a question about
|
||||
// its content via the LLM extractor; optionally compare a
|
||||
// numeric/string result.
|
||||
// signal — fire when a new mailbox signal (existing IMAP watchers)
|
||||
// matches an optional keyword.
|
||||
type Condition struct {
|
||||
Type string `json:"type"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Question string `json:"question,omitempty"`
|
||||
Op string `json:"op,omitempty"` // any|lt|lte|gt|gte|eq|contains
|
||||
Threshold float64 `json:"threshold,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Keyword string `json:"keyword,omitempty"`
|
||||
}
|
||||
|
||||
// Action types:
|
||||
//
|
||||
// notify — deliver through one of the owner's notification channels.
|
||||
// email — send one email to a fixed recipient via the server relay.
|
||||
// bookmark — save a URL as the owner's bookmark.
|
||||
type Action struct {
|
||||
Type string `json:"type"`
|
||||
ChannelID string `json:"channelId,omitempty"`
|
||||
To string `json:"to,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Body string `json:"body,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
var numericOps = map[string]bool{"lt": true, "lte": true, "gt": true, "gte": true}
|
||||
|
||||
// ValidateSpec is the trust boundary: compiled (or hand-written) specs pass
|
||||
// through here on EVERY write and again nowhere else — the engine executes
|
||||
// only stored, validated rows.
|
||||
func ValidateSpec(s *Spec) error {
|
||||
switch s.Condition.Type {
|
||||
case "url_watch":
|
||||
u, err := url.Parse(strings.TrimSpace(s.Condition.URL))
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return errors.New("condition.url must be an absolute http(s) URL")
|
||||
}
|
||||
s.Condition.URL = u.String()
|
||||
if q := strings.TrimSpace(s.Condition.Question); q == "" || len([]rune(q)) > 500 {
|
||||
return errors.New("condition.question is required (max 500 chars)")
|
||||
}
|
||||
switch s.Condition.Op {
|
||||
case "", "any":
|
||||
s.Condition.Op = "any"
|
||||
case "lt", "lte", "gt", "gte":
|
||||
// threshold 0 is meaningful (e.g. "any price below 0" never fires,
|
||||
// but "gt 0" is fine); numeric ops just need the op set.
|
||||
case "eq", "contains":
|
||||
if strings.TrimSpace(s.Condition.Text) == "" {
|
||||
return errors.New("condition.text is required for eq/contains")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown condition.op %q", s.Condition.Op)
|
||||
}
|
||||
case "signal":
|
||||
if len([]rune(s.Condition.Keyword)) > 200 {
|
||||
return errors.New("condition.keyword too long")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown condition.type %q (url_watch or signal)", s.Condition.Type)
|
||||
}
|
||||
|
||||
switch s.Action.Type {
|
||||
case "notify":
|
||||
if strings.TrimSpace(s.Action.ChannelID) == "" {
|
||||
return errors.New("action.channelId is required for notify")
|
||||
}
|
||||
case "email":
|
||||
to := strings.TrimSpace(s.Action.To)
|
||||
if a, err := mail.ParseAddress(to); err != nil || a.Address != to {
|
||||
return errors.New("action.to must be a valid email address")
|
||||
}
|
||||
s.Action.To = to
|
||||
case "bookmark":
|
||||
u, err := url.Parse(strings.TrimSpace(s.Action.URL))
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return errors.New("action.url must be an absolute http(s) URL for bookmark")
|
||||
}
|
||||
if strings.TrimSpace(s.Action.Title) == "" {
|
||||
return errors.New("action.title is required for bookmark")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown action.type %q (notify, email or bookmark)", s.Action.Type)
|
||||
}
|
||||
if t := strings.TrimSpace(s.Action.Title); len([]rune(t)) > 200 {
|
||||
return errors.New("action.title too long (max 200)")
|
||||
}
|
||||
if b := s.Action.Body; len([]rune(b)) > 4000 {
|
||||
return errors.New("action.body too long (max 4000)")
|
||||
}
|
||||
|
||||
// Poll floor protects targets and the AI budget; default 60.
|
||||
if s.PollMinutes == 0 {
|
||||
s.PollMinutes = 60
|
||||
}
|
||||
if s.PollMinutes < 15 || s.PollMinutes > 7*24*60 {
|
||||
return errors.New("pollMinutes must be between 15 and 10080")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Summary renders a spec as one human sentence (UI + logs; never contains
|
||||
// secrets — specs hold no credentials by construction).
|
||||
func Summary(s Spec) string {
|
||||
var cond string
|
||||
switch s.Condition.Type {
|
||||
case "url_watch":
|
||||
cond = fmt.Sprintf("watch %s — %q", s.Condition.URL, s.Condition.Question)
|
||||
if numericOps[s.Condition.Op] {
|
||||
cond += fmt.Sprintf(" [%s %g]", s.Condition.Op, s.Condition.Threshold)
|
||||
} else if s.Condition.Op == "contains" || s.Condition.Op == "eq" {
|
||||
cond += fmt.Sprintf(" [%s %q]", s.Condition.Op, s.Condition.Text)
|
||||
}
|
||||
case "signal":
|
||||
cond = "a new mailbox signal arrives"
|
||||
if s.Condition.Keyword != "" {
|
||||
cond += fmt.Sprintf(" matching %q", s.Condition.Keyword)
|
||||
}
|
||||
}
|
||||
var act string
|
||||
switch s.Action.Type {
|
||||
case "notify":
|
||||
act = "notify me"
|
||||
case "email":
|
||||
act = "email " + s.Action.To
|
||||
case "bookmark":
|
||||
act = "save a bookmark"
|
||||
}
|
||||
return "When " + cond + ", " + act + "."
|
||||
}
|
||||
Reference in New Issue
Block a user