Files
superbrain/internal/ai/ai.go
T
Andrew S Erwin 2037a04817
release gate / check (push) Failing after 6m37s
Add agent automations: 'hey superbrain' NL-compiled watch-and-act tasks
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.
2026-10-27 22:54:25 -05:00

196 lines
5.3 KiB
Go

// Package ai is the LLM gateway (AI features phase 1). One OpenAI-compatible
// chat-completions client pointed at OpenRouter by default; any
// OpenAI-compatible endpoint works via AI_BASE_URL (house Core gateway,
// Ollama, etc.).
//
// Rules this package exists to enforce:
// - the API key lives ONLY in env (.env), never in the repo or logs;
// - every dial goes through netguard + an outbound budget, like all
// server-initiated work;
// - model output is never trusted: callers parse it through
// ExtractJSON + schema validation (see internal/agent).
package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/superbrain/internal/outbound"
)
// DefaultModel is the phase-1 free OpenRouter model. Override with AI_MODEL.
const DefaultModel = "recursive/flint-v1.0:free"
const defaultBaseURL = "https://openrouter.ai/api/v1"
// ErrNotConfigured means AI_API_KEY is unset; callers answer 503 (a global
// deployment property, not a per-user signal).
var ErrNotConfigured = errors.New("ai: not configured (AI_API_KEY is unset)")
type Config struct {
APIKey string
Model string
BaseURL string
}
func LoadConfig() Config {
model := strings.TrimSpace(os.Getenv("AI_MODEL"))
if model == "" {
model = DefaultModel
}
base := strings.TrimSpace(os.Getenv("AI_BASE_URL"))
if base == "" {
base = defaultBaseURL
}
return Config{APIKey: strings.TrimSpace(os.Getenv("AI_API_KEY")), Model: model, BaseURL: strings.TrimRight(base, "/")}
}
func Configured() bool { return LoadConfig().APIKey != "" }
// client dials through netguard (public ranges + 443/80 only unless the
// operator pinned the host or allowed private ranges) — the AI endpoint is
// operator-configured, but the discipline is uniform for every server dial.
var client = &http.Client{
Timeout: 90 * time.Second,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, network, address)
}
return netguard.DialContextPorts(ctx, network, address, 80, 443)
},
IdleConnTimeout: 30 * time.Second,
MaxIdleConns: 8,
MaxIdleConnsPerHost: 4,
},
}
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
// Complete sends one system+user exchange and returns the assistant text.
// Bounded by the shared outbound budget so a slow provider cannot pile up
// goroutines.
func Complete(ctx context.Context, system, user string) (string, error) {
cfg := LoadConfig()
if cfg.APIKey == "" {
return "", ErrNotConfigured
}
release, _, ok := outbound.Reserve("ai", 10, time.Minute)
if !ok {
return "", errors.New("ai: busy, try again shortly")
}
defer release()
payload, err := json.Marshal(map[string]any{
"model": cfg.Model,
"messages": []chatMessage{
{Role: "system", Content: system},
{Role: "user", Content: user},
},
})
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.BaseURL+"/chat/completions", bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+cfg.APIKey)
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := io.ReadAll(io.LimitReader(res.Body, 2<<20))
if err != nil {
return "", err
}
if res.StatusCode != 200 {
// Never echo the response body wholesale: it can reflect the key or
// account details. Status + a short prefix is enough to debug.
return "", fmt.Errorf("ai: provider answered %d: %s", res.StatusCode, truncate(string(body), 200))
}
var out struct {
Choices []struct {
Message chatMessage `json:"message"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(body, &out); err != nil {
return "", fmt.Errorf("ai: unreadable provider response: %w", err)
}
if out.Error != nil {
return "", fmt.Errorf("ai: provider error: %s", truncate(out.Error.Message, 200))
}
if len(out.Choices) == 0 {
return "", errors.New("ai: provider returned no choices")
}
return out.Choices[0].Message.Content, nil
}
// ExtractJSON pulls the first balanced JSON object out of a model reply
// (models wrap JSON in prose or code fences despite instructions).
func ExtractJSON(s string) (json.RawMessage, error) {
if i := strings.Index(s, "```"); i >= 0 {
// Prefer a fenced block when present.
rest := s[i+3:]
if j := strings.Index(rest, "```"); j > 0 {
s = rest[:j]
}
}
start := strings.Index(s, "{")
if start < 0 {
return nil, errors.New("ai: no JSON object in model reply")
}
depth := 0
inStr := false
esc := false
for i := start; i < len(s); i++ {
c := s[i]
switch {
case inStr:
if esc {
esc = false
} else if c == '\\' {
esc = true
} else if c == '"' {
inStr = false
}
case c == '"':
inStr = true
case c == '{':
depth++
case c == '}':
depth--
if depth == 0 {
return json.RawMessage(s[start : i+1]), nil
}
}
}
return nil, errors.New("ai: unbalanced JSON in model reply")
}
func truncate(s string, n int) string {
rs := []rune(s)
if len(rs) <= n {
return s
}
return string(rs[:n])
}