Add agent automations: 'hey superbrain' NL-compiled watch-and-act tasks
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:
Andrew S Erwin
2026-10-27 22:54:25 -05:00
parent 2f89719f0a
commit 2037a04817
17 changed files with 1964 additions and 4 deletions
+282
View File
@@ -0,0 +1,282 @@
'use client'
// Automations ("hey superbrain"): compile a natural-language request into a
// validated task proposal, let the user confirm/edit it, then manage tasks
// and watch their runs. The server compiles AND re-validates; this UI never
// treats the model's output as trusted — the proposal is shown in plain
// language plus its raw spec before anything is stored.
import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Sparkles, Trash2, Play, Loader2, Wand2 } from 'lucide-react'
import { SafeTime } from '@/components/safe-format'
import { toast } from 'sonner'
type Condition = {
type: string; url?: string; question?: string; op?: string
threshold?: number; text?: string; keyword?: string
}
type ActionT = {
type: string; channelId?: string; to?: string
title?: string; body?: string; url?: string
}
type Spec = { condition: Condition; action: ActionT; pollMinutes: number; once: boolean }
type Task = {
id: string; name: string; spec: Spec; summary: string; enabled: boolean
status: string; fireCount: number; lastCheckedAt: string | null
lastFiredAt: string | null; version: number; createdAt: string
}
type Run = { id: string; taskId: string; outcome: string; detail: string | null; createdAt: string }
type ChannelOption = { id: string; name: string; kind: string; enabled: boolean }
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function AutomationsSettings() {
const [tasks, setTasks] = useState<Task[]>([])
const [runs, setRuns] = useState<Run[]>([])
const [channels, setChannels] = useState<ChannelOption[]>([])
const [loading, setLoading] = useState(true)
const [available, setAvailable] = useState(true)
// Composer state
const [text, setText] = useState('')
const [compiling, setCompiling] = useState(false)
const [proposal, setProposal] = useState<{ name: string; spec: Spec; summary: string } | null>(null)
const [showRaw, setShowRaw] = useState(false)
const [runningId, setRunningId] = useState<string | null>(null)
const reload = useCallback(() =>
Promise.all([
api('/api/agent/tasks').then(r => r.json()),
api('/api/agent/runs').then(r => r.json()),
api('/api/notifications/channels').then(r => r.json()),
])
.then(([tk, rn, ch]) => {
if (Array.isArray(tk)) setTasks(tk)
if (Array.isArray(rn)) setRuns(rn.slice(0, 10))
if (Array.isArray(ch)) setChannels(ch)
})
.catch(() => { toast.error('Could not load automations') })
.finally(() => { setLoading(false) }), [])
useEffect(() => { reload() }, [reload])
const reportError = async (res: Response, fallback: string): Promise<string | null> => {
let msg = fallback
try {
const data = await res.json()
if (data?.error) msg = data.error
} catch { /* non-JSON body */ }
if (res.status === 503) setAvailable(false)
toast.error(msg)
return msg
}
const compile = async () => {
if (!text.trim()) { toast.error('Describe what should happen first'); return }
setCompiling(true)
setProposal(null)
try {
const res = await api('/api/agent/compile', { method: 'POST', body: JSON.stringify({ text }) })
if (res.ok) {
const data = await res.json()
setProposal({ name: data.name, spec: data.spec, summary: data.summary })
setAvailable(true)
} else {
await reportError(res, 'Could not understand that request')
}
} catch {
toast.error('Could not reach the AI service')
} finally {
setCompiling(false)
}
}
const createTask = async () => {
if (!proposal) return
// A compiled notify action has no channel id (the model never knows
// them); the user must pick one before creation.
if (proposal.spec.action.type === 'notify' && !proposal.spec.action.channelId) {
toast.error('Pick a notification channel for this task')
return
}
const res = await api('/api/agent/tasks', {
method: 'POST',
body: JSON.stringify({ name: proposal.name, spec: proposal.spec }),
})
if (res.ok) {
toast.success('Automation created')
setProposal(null)
setText('')
await reload()
} else {
await reportError(res, 'Could not create the automation')
}
}
const toggleTask = async (t: Task, enabled: boolean) => {
const res = await api(`/api/agent/tasks/${t.id}`, {
method: 'PATCH', body: JSON.stringify({ enabled, version: t.version }),
})
if (res.ok) await reload()
else await reportError(res, 'Could not update the task')
}
const runNow = async (t: Task) => {
setRunningId(t.id)
try {
const res = await api(`/api/agent/tasks/${t.id}/run`, { method: 'POST' })
if (res.ok) {
const data = await res.json()
toast.info(`Run finished: ${data.outcome}`)
await reload()
} else {
await reportError(res, 'Run failed')
}
} finally { setRunningId(null) }
}
const removeTask = async (t: Task) => {
const res = await api(`/api/agent/tasks/${t.id}`, { method: 'DELETE' })
if (res.ok) { toast.success('Automation deleted'); await reload() }
else await reportError(res, 'Could not delete the task')
}
if (loading) {
return <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> Loading automations…</div>
}
return (
<div className="space-y-6">
{/* Composer */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Hey Superbrain</h3>
<p className="text-xs text-muted-foreground">
Describe an automation in plain language. Superbrain compiles it into a task you review
before anything is saved. It can watch a public web page and answer one question about it
(prices, availability, a phrase), or react to new mailbox signals — then notify you,
email someone, or save a bookmark. It cannot log in to sites, book anything, or chain
multiple sites yet.
</p>
{!available && (
<p className="text-xs text-destructive">
AI is not configured on this server (AI_API_KEY missing), so compilation is unavailable.
Tasks with signal conditions still run.
</p>
)}
<Textarea
placeholder='e.g. "when the round trip on https://flights.example/q/123 drops below $400, email david@email.com"'
value={text}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setText(e.target.value)}
rows={3}
/>
<div className="flex gap-2">
<Button onClick={compile} loading={compiling} size="sm" className="gap-1.5">
<Wand2 className="h-3.5 w-3.5" /> Compile
</Button>
{proposal && (
<Button variant="outline" size="sm" onClick={() => setShowRaw(v => !v)}>
{showRaw ? 'Hide details' : 'Review details'}
</Button>
)}
</div>
{proposal && (
<div className="space-y-3 rounded-md border bg-muted/30 p-3">
<div>
<p className="text-sm font-medium">{proposal.name}</p>
<p className="text-sm text-muted-foreground">{proposal.summary}</p>
<p className="text-xs text-muted-foreground mt-1">
Checks every {proposal.spec.pollMinutes} min
{proposal.spec.once ? ' · one-shot (completes after firing)' : ' · ongoing'}
</p>
</div>
{proposal.spec.action.type === 'notify' && (
<Select
value={proposal.spec.action.channelId || ''}
onValueChange={(v: string) => setProposal(p => p ? {
...p,
spec: { ...p.spec, action: { ...p.spec.action, channelId: v } },
} : p)}
>
<SelectTrigger aria-label="Notification channel"><SelectValue placeholder="Choose a notification channel" /></SelectTrigger>
<SelectContent>
{channels.filter(c => c.enabled).map(c => (
<SelectItem key={c.id} value={c.id}>{c.name} ({c.kind})</SelectItem>
))}
</SelectContent>
</Select>
)}
{proposal.spec.action.type === 'email' && (
<Input
aria-label="Recipient"
value={proposal.spec.action.to ?? ''}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setProposal(p => p ? {
...p,
spec: { ...p.spec, action: { ...p.spec.action, to: e.target.value } },
} : p)}
/>
)}
{showRaw && (
<pre className="text-xs bg-background rounded border p-2 overflow-x-auto">{JSON.stringify(proposal.spec, null, 2)}</pre>
)}
<div className="flex gap-2">
<Button size="sm" onClick={createTask}>Create automation</Button>
<Button size="sm" variant="ghost" onClick={() => setProposal(null)}>Discard</Button>
</div>
</div>
)}
</div>
{/* Tasks */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium">Automations</h3>
{tasks.length === 0 && <p className="text-sm text-muted-foreground">No automations yet.</p>}
{tasks.map(t => (
<div key={t.id} className="flex items-center gap-3 rounded-md border p-3">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{t.name}</p>
<p className="text-xs text-muted-foreground truncate">{t.summary}</p>
<p className="text-xs text-muted-foreground">
every {t.spec.pollMinutes}m · fired {t.fireCount}×
{t.lastFiredAt ? <> · last fired <SafeTime date={t.lastFiredAt} localize /></> : ''}
</p>
</div>
<Badge variant={t.status === 'active' ? 'default' : t.status === 'done' ? 'secondary' : 'destructive'}>
{t.status}
</Badge>
<Button size="sm" variant="outline" onClick={() => runNow(t)} disabled={runningId === t.id} aria-label="Run now">
{runningId === t.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
</Button>
<Switch checked={t.enabled} onCheckedChange={(v: boolean) => toggleTask(t, v)} aria-label="Enable automation" />
<Button size="sm" variant="ghost" onClick={() => removeTask(t)} aria-label="Delete automation">
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
</Button>
</div>
))}
</div>
{/* Runs */}
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium">Recent runs</h3>
{runs.length === 0 && <p className="text-sm text-muted-foreground">Nothing has run yet.</p>}
{runs.map(rn => (
<div key={rn.id} className="flex items-center gap-2 text-sm">
<Badge variant={rn.outcome === 'fired' ? 'default' : rn.outcome === 'failed' ? 'destructive' : 'secondary'}>
{rn.outcome}
</Badge>
<span className="truncate flex-1 text-muted-foreground">{rn.detail ?? ''}</span>
<span className="text-xs text-muted-foreground shrink-0"><SafeTime date={rn.createdAt} localize /></span>
</div>
))}
</div>
</div>
)
}