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,121 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/andrew/superbrain/internal/ai"
|
||||
)
|
||||
|
||||
// ErrCompileRejected means the model could not (or refused to) express the
|
||||
// request as a task. The message is safe to show the user verbatim.
|
||||
type ErrCompileRejected struct{ Reason string }
|
||||
|
||||
func (e *ErrCompileRejected) Error() string { return "compile rejected: " + e.Reason }
|
||||
|
||||
// compileSystem is the compiler contract. The model gets a closed schema,
|
||||
// worked examples, and an explicit refusal path — it never gets to invent
|
||||
// actions. Everything it returns is re-validated by ValidateSpec; the
|
||||
// prompt is convenience, the validator is the boundary.
|
||||
const compileSystem = `You are Superbrain's automation compiler. Convert the user's request into ONE automation task, or refuse.
|
||||
|
||||
Reply with ONLY a JSON object, no prose:
|
||||
{"name": "<short task name>", "spec": <Spec>} on success
|
||||
{"error": "<one sentence, user-facing>"} when the request cannot be expressed.
|
||||
|
||||
Spec schema:
|
||||
{
|
||||
"condition": {
|
||||
"type": "url_watch" | "signal",
|
||||
"url": absolute http(s) URL to poll (url_watch only),
|
||||
"question": what to look for on the page, <=500 chars (url_watch only),
|
||||
"op": "any" | "lt" | "lte" | "gt" | "gte" | "eq" | "contains",
|
||||
"threshold": number for lt/lte/gt/gte,
|
||||
"text": string for eq/contains,
|
||||
"keyword": optional keyword filter (signal only)
|
||||
},
|
||||
"action": {
|
||||
"type": "notify" | "email" | "bookmark",
|
||||
"channelId": existing notification channel id (notify only; you do NOT know ids - put "" and the user picks one),
|
||||
"to": recipient email (email only),
|
||||
"title": message/bookmark title,
|
||||
"body": message body,
|
||||
"url": URL to save (bookmark only)
|
||||
},
|
||||
"pollMinutes": 15..10080 (default 60),
|
||||
"once": true for one-shot deals, false for ongoing watches
|
||||
}
|
||||
|
||||
What Superbrain can actually do — anything else MUST be refused:
|
||||
- url_watch: fetch a PUBLIC web page on a schedule and answer one question
|
||||
about it (prices, availability, a phrase). It cannot log in, search
|
||||
engines, book anything, or chain multiple sites. Multi-step requests
|
||||
(e.g. "watch flights AND then search hotels") must be refused with an
|
||||
explanation that one watch per task is supported today.
|
||||
- signal: fire when the user's existing mailbox watchers produce a new
|
||||
signal, optionally filtered by keyword.
|
||||
- Actions: notify (an existing channel), email (one message to one fixed
|
||||
recipient), bookmark (save one URL for the user).
|
||||
|
||||
Examples:
|
||||
- "when the denver-indy round trip on https://flights.example/q/123 drops below 400, email david@email.com" ->
|
||||
{"name":"Flights DEN-IND under $400","spec":{"condition":{"type":"url_watch","url":"https://flights.example/q/123","question":"What is the cheapest round-trip flight price shown, in USD?","op":"lt","threshold":400},"action":{"type":"email","channelId":"","to":"david@email.com","title":"Flight deal: DEN-IND under $400","body":"A round-trip flight dropped below $400."},"pollMinutes":60,"once":true}}
|
||||
- "tell me when my inbox gets an invoice" ->
|
||||
{"name":"Invoice signals","spec":{"condition":{"type":"signal","keyword":"invoice"},"action":{"type":"notify","channelId":""},"pollMinutes":15,"once":false}}
|
||||
- "book me a hotel" -> {"error":"Superbrain cannot book anything; it can watch a public page and notify you."}
|
||||
|
||||
Rules: prefer once=true for deals and once=false for ongoing watches;
|
||||
pollMinutes>=15 (60 unless the user asks for faster); never invent URLs the
|
||||
user did not provide — if a watch target is missing, refuse and ask for it;
|
||||
keep names under 80 characters.`
|
||||
|
||||
// Compile turns one natural-language request into a validated task
|
||||
// proposal. The result is NOT persisted — the user confirms it through the
|
||||
// regular task-creation endpoint, which validates again.
|
||||
func Compile(ctx context.Context, text string) (name string, spec Spec, err error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return "", Spec{}, errors.New("empty request")
|
||||
}
|
||||
if len([]rune(text)) > 2000 {
|
||||
return "", Spec{}, errors.New("request too long (max 2000 characters)")
|
||||
}
|
||||
reply, err := ai.Complete(ctx, compileSystem, text)
|
||||
if err != nil {
|
||||
return "", Spec{}, err
|
||||
}
|
||||
raw, err := ai.ExtractJSON(reply)
|
||||
if err != nil {
|
||||
return "", Spec{}, fmt.Errorf("model reply was not JSON: %w", err)
|
||||
}
|
||||
var out struct {
|
||||
Name string `json:"name"`
|
||||
Spec *Spec `json:"spec"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return "", Spec{}, fmt.Errorf("model reply did not match the compiler schema: %w", err)
|
||||
}
|
||||
if out.Error != "" {
|
||||
return "", Spec{}, &ErrCompileRejected{Reason: out.Error}
|
||||
}
|
||||
if out.Spec == nil {
|
||||
return "", Spec{}, &ErrCompileRejected{Reason: "the model returned neither a task nor an explanation"}
|
||||
}
|
||||
name = strings.TrimSpace(out.Name)
|
||||
if name == "" {
|
||||
name = "Automation"
|
||||
}
|
||||
if len([]rune(name)) > 120 {
|
||||
name = string([]rune(name)[:120])
|
||||
}
|
||||
// The validator, not the model, decides what a task is.
|
||||
if err := ValidateSpec(out.Spec); err != nil {
|
||||
return "", Spec{}, &ErrCompileRejected{Reason: "the proposed task failed validation: " + err.Error()}
|
||||
}
|
||||
// A compiled notify action never knows channel ids; the UI fills it in.
|
||||
return name, *out.Spec, nil
|
||||
}
|
||||
Reference in New Issue
Block a user