Chaining: spec gains calls:[ids] + calledOnly. On fire, a task calls its
same-owner callees in order; each callee evaluates its OWN condition and
may call onward. Safety: write-time cycle rejection (owner-graph DFS) plus
a runtime visited-set + depth cap (5); calledOnly tasks skip the schedule;
existing per-task fire caps and the owner daily email cap still apply
across the chain. The LLM never chooses calls — the user wires the graph.
Refinements: AgentTask.refinements jsonb (migration 026) stores added
constraints; the UI composes prompt+refinements into the compile text and
shows removable chips. Dry run: condition-check is split from fire() so
POST /api/agent/dry-run evaluates a spec without acting or recording —
the 'Extend → Try it' preview ('result would be false right now').
UI: detail view gains the 'If true, call' card (picker disables
loop-creating options), refinement chips + Extend/Try it/Add flow, called-by
breadcrumb, and a 'when called' frequency label.
Verified: full DB integration suite under -race (chaining fires callees,
cycle rejected at write + runtime guard terminates a DB-injected cycle,
calledOnly skips schedule, dry run records nothing, refinements capped),
db-converge + atomicity, web lint/SSR/build, browser regression extended
for chaining + refinement + dry run.
205 lines
7.4 KiB
Go
205 lines
7.4 KiB
Go
// 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"`
|
|
// Phase 2 chaining: when this task's condition is true and its action
|
|
// fires, it calls these tasks (by id, same owner) in order. Each callee
|
|
// evaluates its OWN condition. CalledOnly tasks skip the schedule and
|
|
// run only when called (or via manual Run now). Cycles are rejected at
|
|
// write time AND guarded at runtime (visited set + depth cap).
|
|
Calls []string `json:"calls,omitempty"`
|
|
CalledOnly bool `json:"calledOnly,omitempty"`
|
|
}
|
|
|
|
// MaxChainDepth bounds how deep a call chain may recurse at runtime; the
|
|
// write-time cycle check is the primary gate, this is defense in depth.
|
|
const MaxChainDepth = 5
|
|
|
|
// MaxCalls bounds the callees one task may list.
|
|
const MaxCalls = 10
|
|
|
|
// 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")
|
|
}
|
|
|
|
// Chaining local rules: non-empty ids, no self-call, no duplicates,
|
|
// bounded count. Cross-task ownership and cycle checks live in the
|
|
// handler (they need the owner's whole graph); the engine adds a
|
|
// runtime visited-set + depth cap as defense in depth.
|
|
if len(s.Calls) > MaxCalls {
|
|
return fmt.Errorf("calls may list at most %d automations", MaxCalls)
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, id := range s.Calls {
|
|
id = strings.TrimSpace(id)
|
|
if id == "" {
|
|
return errors.New("calls entries must be non-empty task ids")
|
|
}
|
|
if seen[id] {
|
|
return errors.New("calls contains a duplicate automation")
|
|
}
|
|
seen[id] = true
|
|
}
|
|
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 + "."
|
|
}
|